struct Person {
let firstName: String
let lastName: String
init!(firstName: String, lastName: String) {
guard !firstName.isEmpty && !lastName.isEmpty else {
return nil
}
self.firstName = firstName
self.lastName = lastName
}
}
swift 2.x
let nilPerson = Person(firstName: "", lastName: "Mathias")
nilPerson.firstName // `nilPerson ` 是 `Person!`类型,值为nil,程序崩溃!
let matt = Person(firstName: "Matt", lastName: "Mathias")
matt.firstName // `matt` 是 `Person!`类型
let anotherMatt = matt // `anotherMatt` 也是 `Person!`类型
swift 3
let nilPerson = Person(firstName: "", lastName: "Mathias")
nilPerson?.firstName// `nilPerson ` 是 `Person?`类型,可选链,安全!
let matt = Person(firstName: "Matt", lastName: "Mathias")
matt?.firstName // `matt` 是 `Person?`类型
let anotherMatt = matt // `anotherMatt` 也是 `Person?`类型
let runningWithScissors: Person! = Person(firstName: "Edward", lastName: "") // 显式声明为` Person!`类型
let safeAgain = runningWithScissors // `safeAgain ` 是 `Person?`类型
- 依靠编译器对类型进行推断
- 总结:引用
Optional
或 ImplicitlyUnwrappedOptional
类型,自己会变成 Optional
类型。
参考资料
WWDC 2016: Increased Safety in Swift 3.0