环境Xcode 11.0 beta4 swift 5.1
nil
定义一个可选项是在类型后面加个?
var name: String? = "Me"
name = nil
var age: Int? // 默认是nil
age = 99
age = nil
Swift的nil不等于Objective-C中的nil。在Objective-C中,nil是指向不存在对象的指针。在Swift中,nil不是指针,它是某种类型缺少具体的值。任何可选类型都可以设置为nil,而不仅仅是对象类型。
可以配合if
语句使用,可以通过==
或者 !=
,如果一个可选项有值,将被认为 != nil
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber 被编译器推导为类型 "Int?" 或者 "optional Int"
if convertedNumber != nil {
print("convertedNumber contains some integer value.")
}
// Prints "convertedNumber contains some integer value."
可选项强制解包还可以使用!
,如果此时可选项值为nil
,将会产生运行时错误
var age: Int? = 10
let age2: Int = age!
可以用来判断可选项是否包含值,如果有值,赋值给一个临时的变量(可以用let
or var
来修饰)并返回true
,否则返回 false
if let actualNumber = Int(possibleNumber) {
print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
print("The string \"\(possibleNumber)\" could not be converted to an integer")
}
// "123"可以转换成Int类型数值123
// Prints "The string "123" has an integer value of 123"
if
语句中多个可选项是否有值的判断,多个条件可以用,
分割,这种情况等价多个条件使用&&
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
// Prints "4 < 42 < 100"
if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
}
}
// Prints "4 < 42 < 100"
// 以上两种写法是等价的
在if语句中使用可选绑定创建的常量和变量只能在if语句的主体中使用。相反,使用guard语句创建的常量和变量可以在guard语句后面的代码行中使用
!
,这样每次使用时不需要在变量后面加上!
,你可以认为是可选项在使用时自动解包nil
,此时如果使用一样会触发一个运行时的错误,与强制解包一个nil
值是一样的if
高速公路来判断隐式解包的可选项也可以用像普通可选项绑定一样绑定
// 1
let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // 强制解包
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // 不需强制解包
// 2
let num1: Int! = nil
let num2: Int = num1 // Fatal error
// 3
if assumedString != nil {
print(assumedString!)
}
// Prints "An implicitly unwrapped optional string."
// 4
if let definiteString = assumedString {
print(definiteString)
}
// Prints "An implicitly unwrapped optional string."
guard
关键字
guard
基本格式
guard 条件 else {
// do something
// 退出当前作用域
// return, break, continue, or throw, fatalError(_:file:line:)
}
guard
语句条件为false
时,执行else
大括号里的语句,条件为true
时,执行大括号后面的语句guard
条件进行可选项绑定时,绑定的变量可以用let
、var
来修饰,也能在外层作用域中使用
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
greet(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino."
原文:https://www.cnblogs.com/tzsh1007/p/11459278.html