iOS

swift - optional 관련

유사앱등이 2022. 4. 26. 02:29

 

Optional value를 다루는 방법들 정리

 

// How to handle Optional

var myOptional: String?

myOptional = "Hello"

// ---wrong
//let text: String = myOptional



// 1. Force Unwrapping : the least safe way

let text: String = myOptional!



// 2. Check for nil value :

if myOptional != nil {
	let text: String = myOptional!
} else {
	print("myOptional : nil")
}



// 3. Optional Binding 
// : use "if let" to bind the value of the optional
//	if it's not nil to a new constant. (within the curly braces)


if let safeOptional = myOptional {
	let text: String = safeOptional
	print(safeOptional)
} else {
	print("myOptional : nil")
}



// 4. Nil Coalescing Operator == "??"
//    : Checks to see if the optional is nil -- if it's nil, then use default value.
// 			==> optional ?? defaultValue

myOptional = nil
let text2: String = myOptional ?? "I am the default value"
print(text2)
 


// --------------Optional class / struct


// 5. Optional Chaining
// : if this optional isn't nil, 
//		then continue along this chain, go ahead, access that property.
// 		==> optional?.property // optional?.method()

struct MyOptionalStruct {
	var property = 123
	func method() {
		print("I am the struct's method.")
	}
}

let myOptionalStruct: MyOptionalStruct? // haven't yet initialized it.

myOptionalStruct = MyOptionalStruct() // initialized.
print(myOptionalStruct?.property)
myOptionalStruct?.method()

'iOS' 카테고리의 다른 글

Xcode ) Storyboard - Object Library  (0) 2022.05.29
swift - 사용자의 위치정보 얻기  (0) 2022.05.26
swift - Extension  (0) 2022.05.13
swift ) 진수 변환  (0) 2022.05.06
swift ) Protocol 관련 정리  (0) 2022.04.28