Nil-Coalescing Operator

장주명·2021년 5월 21일
0

Optionals

목록 보기
4/6

이항 연산자로 왼쪽의 피연산자는 optional이며 오른쪽의 피연산자는 non-optional이고 모두 같은 타입이여야 한다.

?? 뒤에 nil값일때 리턴할 값을 작성한다.

a ?? b
OptionalExpression ?? Expression
var msg = ""

var input : String? = "Swift"

if let inputNmae = input { // input의 nil 유무에 따라 msg의 값이 달라진다.
    msg = "Hello, " + inputNmae
} else {
    msg = "Hello, Stranger"
}

print(msg)

var str = "Hello " + (input != nil ? input! : "Stranger")

print(str) // 위에 코드와 같다. 값이 저장되어있는지 확인하고 값을 추출하는 코드를 작성했다 
              하지만 Nil-Coalescing Operator를 통해 더 효율적으로 작성할수 있다.


str = "Hello, " + (input ?? "Stragner")

print(str) // 위에 조건문과 비슷하지만 더 코드가 짧아졌다. 
              input에 nil값이라면 ?? 뒤에 값을 리턴해준다.
profile
flutter & ios 개발자

0개의 댓글

관련 채용 정보