관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift 공식 문서] 15. Optional Chaining (옵셔널 체이닝) 본문

swift 공식 문서

[iOS - swift 공식 문서] 15. Optional Chaining (옵셔널 체이닝)

jake-kim 2021. 7. 12. 23:12

Optional Chaining

  • 정의: Optional인 것들을 가지고 property나 method, subscript를 쿼리하고 호출하는 프로세스
  • optional값 중 하나가 nil이 되면 nil반환, 단 중단되는게 아닌 해당부분만 nil반환
let someOptoinalProperty: SomeProperty? = nil

print("start") // start
print(someOptoinalProperty?.value) // nil
print("end") // end

Forced Unwrapping의 대안으로 Optional Chaining 사용

  • 런타임 오류에 예방
let roomCount = john.residence!.numberOfRooms
if let roomCount = john.residence?.numberOfRooms {
	print("roomCount")
} else {
	print("Unable to retrieve the number of rooms.")
}

Optional Chaining을 통한 접근

  • property 접근
let john = Person()
if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).")
}

john.residence?.address = someAddress
  • Method 접근
if john.residence?.printNumberOfRooms() != nil {
    print("It was possible to print the number of rooms.")
} else {
    print("It was not possible to print the number of rooms.")
}
  • Subscripts 접근: 인덱스 괄호 전에 '?'를 써주는것을 주의
if let firstRoomName = john.residence?[0].name {
    print("The first room name is \(firstRoomName).")
} else {
    print("Unable to retrieve the first room name.")
}
  • Dictionary에서의 Optional Chanining
var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0] += 1
testScores["Brian"]?[0] = 72

* 참고

https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html

Comments