func doSomething(data: String?) -> String {
// If data is nil, then return
guard let data = data else { return "Invalid data" }
defer { print("This will always be printed if data isn't nil") }
// data is now a non optional String
if data.lowercaseString == "ok" { return "Data is \"ok\"" }
return "I'm your father"
}
print(doSomething("ok"))
输出:
This will always be returned if data isn't nil
Data is "ok"
更接近你的问题: 保护语句中任何条件的值都必须具有符合BooleanType协议的类型。
func doSomething(data: String) -> String {
guard !data.isEmpty else { return "Data is empty" }
return data
}
print(doSomething("ok")) // ok
print(doSomething("")) // Data is empty
for imageName in imageNamesList {
guard let image = UIImage(named: imageName)
else { continue }
// do something with image
}
func deferExample() {
defer {
print(“This will be run last”)
}
defer {
print(“This will be run second-last”)
}
print(“operation started”)
// …
print(“operation complete”)
}
class MySampleClass {
var sampleString:String?
func printSampleString() -> Void {
if let str = sampleString{ ///if sampleString is nil the if will escape
print(str) ///sampleString is not nil
}
}
}
var obj : MySampleClass = MySampleClass()
obj.sampleString = "SampleString"///Assign value to sampleString
obj.printSampleString()
现在,让我们来看看guard方法
class MySampleClass {
var sampleString:String?
func printSampleString() -> Void {
guard let str = sampleString else { ///guard will ensure sampleString is not nil
return ///if sampleString is nil,then return
}
print(str) //sampleString is not nil,so print str!
}
}
var obj : MySampleClass = MySampleClass()
obj.sampleString = "SampleString"///Assign value to sampleString
obj.printSampleString()
4条答案
按热度按时间wgx48brx1#
如果一个或多个条件不满足,guard语句用于将程序控制转移到作用域之外。
输出:
更接近你的问题:
保护语句中任何条件的值都必须具有符合BooleanType协议的类型。
bq8i3lrv2#
您也可以使用guards,这样代码可读性会更好,
zysjyyx43#
1.在guard中,一旦选择项成功展开,展开的值就可以供后续程式码使用,而Defer则可用于执行无条件清除,不论某些作业是否成功。
1.两者都用于控制流和错误处理
使用保护延迟(& D):
请看http://nstechstack.com/archives/question/223-1
p1tboqfb4#
让我们来了解一下非常简单的
if
方法。现在,让我们来看看
guard
方法