像 if 语句一样,guard 的执行取决于一个表达式的布尔值。我们可以使用 guard 语句来要求条件必须为真时,以执行 guard 语句后的代码。不同于 if 语句,一个 guard 语句总是有一个 else 从句,如果条件不为真
则执行 else 从句中的代码。
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).")
}
当 person["name"]
为空时 就会进入guard语句的else从句执行return
再比如下面的写法:
public func unusedFiles() throws -> [FileInfo] {
guard !resourceExtensions.isEmpty else {
throw FengNiaoError.noResourceExtension
}
guard !searchInFileExtensions.isEmpty else {
throw FengNiaoError.noFileExtension
}
let allResources = allResourceFiles()
let usedNames = allUsedStringNames()
return FengNiao.filterUnused(from: allResources, used: usedNames).map( FileInfo.init )
}
当resourceExtensions.isEmpty
为true
时就会进入 else
从句执行 throw Error
网友评论