Open
Description
语法介绍
Guard Statement
guard condition else {
statements
return
}
示例
func printArea(x: Int, y: Int) {
// Validate that "x" argument is valid.
guard x >= 1 else {
print("X invalid")
return
}
// Validate "y" argument.
guard y >= 1 else {
print("Y invalid")
return
}
// Print area.
let area = x * y
print(area)
}
// Call printArea.
printArea(5, y: 10)
// Use invalid "X" then invalid "Y" arguments.
printArea(0, y: 1)
printArea(2, y: 0)
Output
50
X invalid
Y invalid
错误用法
else
语句块缺失return
,break
,continue
,throw
,fatalError()
等语句
func test(size: Int) {
guard size >= 10 else {
print(1)
}
print(2)
}
Output
'guard' body may not fall through, consider using 'return' or 'break' to exit the scope
- 缺失
else
关键字
func test(size: Int) {
guard size >= 10 {
print(1)
return
}
print(2)
}
Output
Expected 'else' after 'guard' condition
Guard Optional Binding Statement
guard let constantName = someOptional else {
statements
return
}
示例
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(["name": "John"])
// prints "Hello John!"
// prints "I hope the weather is nice near you."
greet(["name": "Jane", "location": "Cupertino"])
// prints "Hello Jane!"
// prints "I hope the weather is nice in Cupertino."
注意
guard
语句结构中的else
不可缺失,在else
子句中可以使用return
, break
,continue
, throw
,fatalError()
等。当guard
语句条件表达式不为true
时执行else
语句块中的代码。
参考
http://nshipster.cn/guard-and-defer/
http://radex.io/swift/guard/
http://stackoverflow.com/questions/30791488/swift-2-guard-keyword
https://www.hackingwithswift.com/new-syntax-swift-2-guard
http://ericcerney.com/swift-guard-statement/
http://www.codingexplorer.com/the-guard-statement-in-swift-2/
http://stackoverflow.com/questions/32256834/swift-2-0-guard-vs-if-let
https://www.natashatherobot.com/swift-guard-better-than-if/
https://www.codebeaulieu.com/40/How-to-use-Guard-in-Swift-2-to-parse-JSON
http://www.appcoda.com/swift2/
http://www.dotnetperls.com/guard-swift
http://www.dotnetperls.com/keyword-swift