if let
将变量暴露给语句外部是没有意义的:
if let json = ... {
//This code will only run if json is non-nil.
//That means json is guaranteed to be non-nil here.
}
//This code will run whether or not json is nil.
//There is not a guarantee json is non-nil.
您还有其他一些选择,具体取决于您要执行的操作:
您可以将需要的其余代码json
放在if
. 您说您不知道嵌套if
语句是否“聪明甚至可能”。它们是可能的,并且程序员经常使用它们。您也可以将其提取到另一个函数中:
func doStuff(json: String) {
//do stuff with json
}
//...
if let json = ... {
doStuff(json: json)
}
如果您知道JSON 不应该是nil
,您可以使用以下命令强制解包!
:
let json = ...!
您可以使用guard
语句使变量成为全局变量。里面的代码guard
只会在json
is nil
时运行。guard
语句的主体必须退出封闭范围,例如通过抛出错误、从函数返回或带有标记的 break:
//throw an error
do {
guard let json = ... else {
throw SomeError
}
//do stuff with json -- it's guaranteed to be non-nil here.
}
//return from the function
guard let json = ... else {
return
}
//do stuff with json -- it's guaranteed to be non-nil here.
//labeled break
doStuff: do {
guard let json = ... else {
break doStuff
}
//do stuff with json -- it's guaranteed to be non-nil here.
}