optional과 언래핑

얄리루·2021년 1월 26일
0

optional은 들어올 값이 처음에 지정되지 않는다.

? - 이 변수에는 값이 들어갈 수도 있고 아닐 수도 있다(nil)는 뜻

! 는 모든 버튼에 타이틀이 다 달려있으니 안심하라는 뜻, 무조건 변수가 있는 상황이 보장됨

위의 ?와 !를 통해 때에 맞게 변수의 optional을 지정해주어 사용할 수 있다.

var player: String? = nil
player = "jiyoon"
print(player) // Optional(jiyoon)
print(player!) // jiyoon

optional을 unwrapping해주는 방법엔 다섯가지가 있다.

1. 위에서 언급한 "!". 강제 언래핑

-> 간편하지만 강력하다. 개발자가 무조건 nil이 아니라는 것을 보장할 때만 사용해야 하며
만약 nil인 경우 강제 언래핑을 해주면 Xcode에서 에러로 인식하지 못하지만 결과적으로 터미널에서는 error를 리턴한다.
결론) 추천하지 않음

2. for문을 통해 nil인지 아닌지를 체크한다.

if optional != nil{
	optional!
}
정확하지만 장황하다.

3. optional binding

optional = 13
if let safeOptional = optional{
	safeOptional
 } else{
 	print("nil.")
 }

optional이 nil이 아니라면 safeOptional에 13을 넣어주고 nil이라면 nil을 출력해준다.

4. optional이 nil 일 때 default값을 가지게 하는 법(Nil Coalescing Operator)

let text: String = myOptional ?? "I am the default value"

3번 optional binding 의 확장판으로 myOptional이 nil이 아니라면 text에 myOptional값을 넣어주고

nil이라면 ?? 뒤에 넣고싶은 값을 써준다.

5. Optional Chaining

optional type인 인자의 method나 하위인자값에 접근할 때 쓰인다.

class MyOptional{
    var property = 123
    var subProperty: classroom?
}
class classroom{
    var studentNum: Int = 456
}

let newVar = MyOptional()
//case1
if let optnl1 = newVar.subProperty?.studentNum{
    print("optnl1 is ",optnl1)
}else{
    print("nil")
}
//case2(optional chaining)
newVar.subProperty = classroom()
if let optnl1 = newVar.subProperty?.studentNum{
    print("optnl1 is ",optnl1)
}else{
    print("nil")
}

위 코드는 newVar변수에 MyOptional class를 할당하고 subProperty 변수에 subClass인 classroom을 할당하고 classroom 안에 있는 studentNum에 접근하려고 하는 코드이다.

정리해서, newVar = MyOptional -> subProperty(classroom) -> studentNum 인 셈이다.

여기서 classroom은 optional class인데, let newVar로 MyOptional을 초기화해주는 순간, optional class는 nil로 초기화 된다.

따라서 case1을 보면 classroom이 nil로 초기화 되었기 때문에 studentNum도 nil로 인식한다.

optional chaining을 사용해주면

nil이었던 subProperty값에 classroom 인스턴스를 추가해서 newVar를 생성해주어야 올바르게 접근할 수 있다.

newVar.subproperty = classroom()
profile
ios개발자를 꿈꾸는 얄리루입니다~!

0개의 댓글