Tuesday, June 16, 2015

Optionals in Swift

Swift is designed for safety. As Apple mentioned, optionals are an example of the fact that Swift is a type safe language. Swift’s optionals provide compile-time check that would prevent some common programming errors happened at run-time. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift's most powerful features.

optional_binding.swift    Select all
// Optional Binding class Person { var residence: Residence? init(residence:Residence?) { self.residence = residence } } class Residence { var address: Address? init(address:Address?) { self.address = address } } class Address { var buildingNumber: String? var streetName: String? var apartmentNumber: String? init(buildingNumber:String?, streetName: String?, apartmentNumber: String?) { self.buildingNumber = buildingNumber self.streetName = streetName self.apartmentNumber = apartmentNumber } convenience init() { self.init(buildingNumber:"", streetName:"", apartmentNumber:"") } } //let paul = Person(residence: Residence(address: Address())) let paul = Person(residence: Residence(address: Address(buildingNumber: "234", streetName: "Brooke Street", apartmentNumber: "9"))) if let buildNumber = paul.residence?.address?.buildingNumber?.toInt() { println("paul's building number is \(buildNumber)") } // swift 3 syntax as below if let buildNumber = paul.residence?.address?.buildingNumber! { print("paul's building number is \(Int(buildNumber)!)") }

No comments: