[ios_Swift] Optional Binding

이시영·2023년 8월 4일

이번엔 강제 언랩핑(Forced Unwrapping)이 아닌 일반적으로 사용되는 Optional Binding과 Unwrapping 에 대해서 알아보자


우선 문법을 살펴보자면 Optional Binding 은 if 문, while 문, guard 문에서 사용된다.

if let name : Type = Optional Expression {
	statements
}
while let name : Type = Optional Expression {
	statements
}
guard let name : Type = Optional Expression else {
	statements
}

Optional Binding 에서는 값(value)이 오는 위치에 Optional Expression 이 오며 이 부분을 Binding 이라고 부른다.

Optional Binding에서는 값을 자동으로 Unwrapping 하여 상수에 적용시킨다. 그러나 만약 값이 nil 이라면 if 문과 while 문은 다음 문장으로 제어를 넘기고 guard 문은 else 블록이 실행되고 스코프가 끝이난다.

Optional Binding 은 Optional 표현식의 값이 저장되어 있는경우에만 Unwrapping을 하기에 강제추출(forced nuwrapping)로 인한 Optional error 들을 방지하고 더 안전한 코드를 작성할 수 있다.

이제 예시를 들어 Forced unwrapping과 비교해보자

var num :Int? = 123

if let a = num {
	print(a, "Unwrapping")
}
// 123 Unwrapping

if num != nil {
	print(num!, "Forced unwrapping")
}
// 123 Forced unwrapping
 

위의 예시처럼 일반적인 Unwrapping에서는 상수 a 뒤에 '!'를 붙일 필요가 없다. 이미 값을 추출했기 때문이다.

게다가 코드를 더 간단하게 작성할 수 있는데 상수의 이름(Identifier)을 옵셔널의 식별자(Identifier)와 똑같이 만드는 것도 가능하고 심지어 상수의 이름이 같다면 Optional Expression 을 생략할 수도 있다.

var num :Int? = 123

if let num = num {
	print(num)
}
// 123

if let num {
	print(num)
}
// 123

다만 여기서 범위(Scop)를 주의해야 하는데 위에서 if 문과 while 문으로 선언된 상수 num은 if 문 또는 while문 바디 안에서만 사용되는 임시상수이다. 때문에 해당 local Scop 밖에서는 Optional인 변수 num이 사용된다.

var num :Int? = 123

if let num = num {
	print(num, "Applied Unwrapping")
    // 123 Applied Unwrapping
}


print(num, "Optional")
// Optional(123) Optional

Optional Binding은 꼭 let 으로만 선언할 필요는 없다. 핑요시 var 로도 선언이 가능다.
var num :Int? = 123

if var num {
	num = 456
	print(num)
    // 456
}

여러개의 Binding을 동시에 사용할 수도 있다.
var a :Int? = 123

var b : String? = "abc"

if let a, let b, b.count > 3{
	print(a)
}

0개의 댓글