SlideShare una empresa de Scribd logo
1 de 15
swift 0x12
optional chaining
문현진(arnold@css99.co.kr)
오늘은 뭘 바를까? 이번 신상은 뭘까? 궁금한 언니들은 구글 플레이에
서 “마메스"를 검색하세요.
옵셔널 체인
옵셔널 값이 nil인가요?
forced unwrapping
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
let roomCount = john.residence.numberOfRooms
forced unwrapping
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
let roomCount = john.residence.numberOfRooms
Runtime Error
forced unwrapping
nil인지 물어본다. (john.residence == nil)
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has (roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// prints "Unable to retrieve the number of rooms."
forced unwrapping
nil인지 물어본다. (john.residence != nil)
john.residence = Residence()
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has (roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// prints "Unable to retrieve the number of rooms."
옵셔널 체인을 위한 모델 클래스 선언
class Person {
var residence: Residence?
}
class Residence {
var rooms = Room[]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
return rooms[i]
}
func printNumberOfRooms() {
println("The number of rooms is
(numberOfRooms)")
}
var address: Address?
}
옵셔널 체인을 위한 모델 클래스 선언
class Room {
let name: String
init(name: String) { self.name = name
}
}
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if buildingName {
return buildingName
} else if buildingNumber {
return buildingNumber
} else {
return nil
}
}
}
옵셔널 체인을 통한 프로퍼티 호출
let john = Person()
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has (roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// prints "Unable to retrieve the number of rooms."
옵셔널 체인을 통한 메소드 호출
func printNumberOfRooms() {
println("The number of rooms is (numberOfRooms)")
}
if john.residence?.printNumberOfRooms() {
println("It was possible to print the number of rooms.")
} else {
println("It was not possible to print the number of rooms.")
}
// prints "It was not possible to print the number of rooms."
옵셔널 체인을 통한 서브스크립트 호출
if let firstRoomName = john.residence?[0].name {
println("The first room name is (firstRoomName).")
} else {
println("Unable to retrieve the first room name.")
}
// prints "Unable to retrieve the first room name."
옵셔널 체인을 통한 서브스크립트 호출
let johnsHouse = Residence()
johnsHouse.rooms += Room(name: "Living Room")
johnsHouse.rooms += Room(name: "Kitchen")
john.residence = johnsHouse
if let firstRoomName = john.residence?[0].name {
println("The first room name is (firstRoomName).")
} else {
println("Unable to retrieve the first room name.")
}
// prints "The first room name is Living Room."
여러 단계의 체인 연결
if let johnsStreet = john.residence?.address?.street {
println("John's street name is (johnsStreet).")
} else {
println("Unable to retrieve the address.")
}
// prints "Unable to retrieve the address."
여러 단계의 체인 연결
let johnsAddress = Address()
johnsAddress.buildingName = "The Larches"
johnsAddress.street = "Laurel Street"
john.residence!.address = johnsAddress
if let johnsStreet = john.residence?.address?.street {
println("John's street name is (johnsStreet).")
} else {
println("Unable to retrieve the address.")
}
// prints "John's street name is Laurel Street."
옵셔널 반환값을 이용한 메소드 체인
if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
println("John's building identifier is (buildingIdentifier).")
}
// prints "John's building identifier is The Larches."
if let upper = john.residence?.address?.buildingIdentifier()?.uppercaseString {
println("John's uppercase building identifier is (upper).")
}
// prints "John's uppercase building identifier is THE LARCHES."

Más contenido relacionado

Más de Hyun Jin Moon

Swift 0x19 advanced operators
Swift 0x19 advanced operatorsSwift 0x19 advanced operators
Swift 0x19 advanced operatorsHyun Jin Moon
 
Swift 0x18 access control
Swift 0x18 access controlSwift 0x18 access control
Swift 0x18 access controlHyun Jin Moon
 
Swift 0x14 nested types
Swift 0x14 nested typesSwift 0x14 nested types
Swift 0x14 nested typesHyun Jin Moon
 
Swift 0x0e 초기화
Swift 0x0e 초기화Swift 0x0e 초기화
Swift 0x0e 초기화Hyun Jin Moon
 
Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트Hyun Jin Moon
 
Swift 0x02 기본 연산자
Swift 0x02   기본 연산자Swift 0x02   기본 연산자
Swift 0x02 기본 연산자Hyun Jin Moon
 
Swift 0x01 환경 설정
Swift 0x01   환경 설정Swift 0x01   환경 설정
Swift 0x01 환경 설정Hyun Jin Moon
 
Shell, merge, heap sort
Shell, merge, heap sortShell, merge, heap sort
Shell, merge, heap sortHyun Jin Moon
 
Programming challange crypt_kicker
Programming challange crypt_kickerProgramming challange crypt_kicker
Programming challange crypt_kickerHyun Jin Moon
 
Node.js Cloud Service Publish
Node.js Cloud Service PublishNode.js Cloud Service Publish
Node.js Cloud Service PublishHyun Jin Moon
 

Más de Hyun Jin Moon (14)

Swift 0x19 advanced operators
Swift 0x19 advanced operatorsSwift 0x19 advanced operators
Swift 0x19 advanced operators
 
Swift 0x18 access control
Swift 0x18 access controlSwift 0x18 access control
Swift 0x18 access control
 
Swift 0x17 generics
Swift 0x17 genericsSwift 0x17 generics
Swift 0x17 generics
 
Swift 0x14 nested types
Swift 0x14 nested typesSwift 0x14 nested types
Swift 0x14 nested types
 
Swift 0x0e 초기화
Swift 0x0e 초기화Swift 0x0e 초기화
Swift 0x0e 초기화
 
Swift 0x0d 상속
Swift 0x0d 상속Swift 0x0d 상속
Swift 0x0d 상속
 
Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트Swift 0x0c 서브스크립트
Swift 0x0c 서브스크립트
 
Swift 0x02 기본 연산자
Swift 0x02   기본 연산자Swift 0x02   기본 연산자
Swift 0x02 기본 연산자
 
Swift 0x01 환경 설정
Swift 0x01   환경 설정Swift 0x01   환경 설정
Swift 0x01 환경 설정
 
Quick, Tree sort
Quick, Tree sortQuick, Tree sort
Quick, Tree sort
 
Shell, merge, heap sort
Shell, merge, heap sortShell, merge, heap sort
Shell, merge, heap sort
 
Djang Beginning 2
Djang Beginning 2Djang Beginning 2
Djang Beginning 2
 
Programming challange crypt_kicker
Programming challange crypt_kickerProgramming challange crypt_kicker
Programming challange crypt_kicker
 
Node.js Cloud Service Publish
Node.js Cloud Service PublishNode.js Cloud Service Publish
Node.js Cloud Service Publish
 

Último

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxnuruddin69
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksMagic Marks
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...Health
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stageAbc194748
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 

Último (20)

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 

Swift 0x12 optional chaining

  • 1. swift 0x12 optional chaining 문현진(arnold@css99.co.kr) 오늘은 뭘 바를까? 이번 신상은 뭘까? 궁금한 언니들은 구글 플레이에 서 “마메스"를 검색하세요.
  • 3. forced unwrapping class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() let roomCount = john.residence.numberOfRooms
  • 4. forced unwrapping class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() let roomCount = john.residence.numberOfRooms Runtime Error
  • 5. forced unwrapping nil인지 물어본다. (john.residence == nil) if let roomCount = john.residence?.numberOfRooms { println("John's residence has (roomCount) room(s).") } else { println("Unable to retrieve the number of rooms.") } // prints "Unable to retrieve the number of rooms."
  • 6. forced unwrapping nil인지 물어본다. (john.residence != nil) john.residence = Residence() if let roomCount = john.residence?.numberOfRooms { println("John's residence has (roomCount) room(s).") } else { println("Unable to retrieve the number of rooms.") } // prints "Unable to retrieve the number of rooms."
  • 7. 옵셔널 체인을 위한 모델 클래스 선언 class Person { var residence: Residence? } class Residence { var rooms = Room[]() var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room { return rooms[i] } func printNumberOfRooms() { println("The number of rooms is (numberOfRooms)") } var address: Address? }
  • 8. 옵셔널 체인을 위한 모델 클래스 선언 class Room { let name: String init(name: String) { self.name = name } } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if buildingName { return buildingName } else if buildingNumber { return buildingNumber } else { return nil } } }
  • 9. 옵셔널 체인을 통한 프로퍼티 호출 let john = Person() if let roomCount = john.residence?.numberOfRooms { println("John's residence has (roomCount) room(s).") } else { println("Unable to retrieve the number of rooms.") } // prints "Unable to retrieve the number of rooms."
  • 10. 옵셔널 체인을 통한 메소드 호출 func printNumberOfRooms() { println("The number of rooms is (numberOfRooms)") } if john.residence?.printNumberOfRooms() { println("It was possible to print the number of rooms.") } else { println("It was not possible to print the number of rooms.") } // prints "It was not possible to print the number of rooms."
  • 11. 옵셔널 체인을 통한 서브스크립트 호출 if let firstRoomName = john.residence?[0].name { println("The first room name is (firstRoomName).") } else { println("Unable to retrieve the first room name.") } // prints "Unable to retrieve the first room name."
  • 12. 옵셔널 체인을 통한 서브스크립트 호출 let johnsHouse = Residence() johnsHouse.rooms += Room(name: "Living Room") johnsHouse.rooms += Room(name: "Kitchen") john.residence = johnsHouse if let firstRoomName = john.residence?[0].name { println("The first room name is (firstRoomName).") } else { println("Unable to retrieve the first room name.") } // prints "The first room name is Living Room."
  • 13. 여러 단계의 체인 연결 if let johnsStreet = john.residence?.address?.street { println("John's street name is (johnsStreet).") } else { println("Unable to retrieve the address.") } // prints "Unable to retrieve the address."
  • 14. 여러 단계의 체인 연결 let johnsAddress = Address() johnsAddress.buildingName = "The Larches" johnsAddress.street = "Laurel Street" john.residence!.address = johnsAddress if let johnsStreet = john.residence?.address?.street { println("John's street name is (johnsStreet).") } else { println("Unable to retrieve the address.") } // prints "John's street name is Laurel Street."
  • 15. 옵셔널 반환값을 이용한 메소드 체인 if let buildingIdentifier = john.residence?.address?.buildingIdentifier() { println("John's building identifier is (buildingIdentifier).") } // prints "John's building identifier is The Larches." if let upper = john.residence?.address?.buildingIdentifier()?.uppercaseString { println("John's uppercase building identifier is (upper).") } // prints "John's uppercase building identifier is THE LARCHES."

Notas del editor

  1. 예를 들어서 옵셔널은 실제로 값이 있을 수도 있고, nil 일 수도 있다. nil인 경우에 강제로 접근하면 fatal error가 난다. 따라서 nil을 자연스럽게 처리 하기 위해서 옵셔널 체인이 있다.
  2. 여기서는 person 의 residence 그리고 residence의 address가 모두 옵셔널이다.
  3. address에는 buildingIdentifier라는 String?을 반환하는 메소드가 있다. 이 메소드는 buildingName, buildingNumber 를 확인해서 nil 을 반환한다.
  4. 이전 처럼 residence가 nil이기 때문에 에러없이 실패한다.
  5. 여기서 printNumberOfRooms는 반환값이 없다. 반환값이 없으면 암시적으로 void를 반환한다. 그러나, 옵셔널변수를 사용하기 떄문에 void가 아니라 void?를 반환 할 것이다. 옵셔널 체인을 통해서 함수를 호출하면 항상 반환 값을 가지기 떄문이다. 그래서 아래 함수가 같이 사용해서 호출이 가능한지 확인 할 수 있다.
  6. 여기서 물음표는 john.residence바로 뒤에 있어야 한다. 왜냐하면 residence가 옵셔널 체인을 사용할 옵션 값이기 떄문이다.
  7. 여기서 물음표는 john.residence바로 뒤에 있어야 한다. 왜냐하면 residence가 옵셔널 체인을 사용할 옵션 값이기 떄문이다.
  8. 여기서 물음표는 john.residence바로 뒤에 있어야 한다. 왜냐하면 residence가 옵셔널 체인을 사용할 옵션 값이기 떄문이다.
  9. 여기서 물음표는 john.residence바로 뒤에 있어야 한다. 왜냐하면 residence가 옵셔널 체인을 사용할 옵션 값이기 떄문이다.
  10. buildingIdentifier()는 원래 String? 타입의 값을 반환한다. 이 이상의 옵셔널 체인을 반환하려면 괄호뒤에 옵셔널 체인 물음표를 쓴다. 왜냐하면 묶으려는 옵셔널 값이 buildingIndentifier가 아니라 buildingIndentifier메소드의 반환 값이기 때문이다.