iOS & Swift 공부 - Optional Binding, Chaining, Nil Coalescing Operator (영)

김영채 (Kevin)·2021년 1월 12일
0

iOS & Swift

목록 보기
21/107
post-thumbnail
  1. Force Unwrapping
  2. Check for nil value
  3. Optional Binding
  4. Nil Coalescing Operator
  5. Optional Chaining

Force Unwrapping

let myOptional: String?
myOptional = "Kevin"

let text: String = myOptional
//error
//text's data type is String, while myOptional's data type is String?
//Two totally different data types

//we can force unwrap using !
let text: String = myOptional!

→ But we need to be careful when using force unwrapping.

→ We need to be really sure that the optional data type is NOT holding a nil value. If it does and we force unwrap, a run time error will occur. (not a compile error)

Check for nil value

let myOptional: String?

myOptional = nil

if myOptional != nil{
	let text: String = myOptional!
  //meaning if myOptional does not have a nil value, it is safe to force unwrap
	//and give the value to "text"
}
else{
	print("optional is nil")
}

→ The problem with the above way is that it's wordy. And you still have to force unwrap it every single time.

Optional Binding

if let safeOptional = optional{
	safeOptional
}
//Caution: it is not ==, it's =

→ We can write an "if let" to bind the value of "optional" if it's not nil, to a new constant (safeOptional). Then, within the curly braces, we can work with the safeOptional

let myOptional: String?

myOptional =  "Kevin"

if let safeOptional = myOptional{
	print(safeOptional)
}
else{
	print("nil value")
}
//Kevin

→ It's like opening a box. Opening myOptional and seeing if it's nil, and if it's not, put it in safeOptional. Otherwise, print nil value.

→ So we are basically checking if the value of myOptional is able to be allocated to safeOptional

Nil Coalescing Operator

  • 2 Question marks
optional ?? defaultValue

→ What does it do? : Checks if optional is nil, and if it's not nil, it uses optional's value, but if it is nil, it uses the defaultValue

let myOptional: String?

myOptional = nil

let text: String = myOptional ?? "default value"

Optional Chaining

  • What if the struct/class is an optional?
struct myOptional{
	var property = 123
	func method(){
		print("method")
	}
}

let myOptional2: myOptional?
//myOptional2 becomes a data type of myOptional? (Optional)

myOptional2 = nil
//the instance is currently not initialized

print(myOptional2.property)
//run time error

print(myOptional2?.property)
//nil (not a run-time error)

myOptional2 = myOptional()
myOptional2?.method()
//method

→ Even though the property and method are not optionals, the struct is right now an optional data type. So we need to unwrap it.

→ This is where we need optional chaining.

optional?.property
optional?.method()
//check if optional is nil, and if it's not nill, continue on
profile
맛있는 iOS 프로그래밍

0개의 댓글