我理解使用optionals足以知道何時必須使用感嘆號打開可選的選項。爲什麼警衛聲明中不需要感嘆號?不使用展開警戒語句
此代碼和編譯但無法使用感嘆號:
struct Blog{
var author:String?
var name: String?
}
func blogInfo2(blog:Blog?){
guard let blog = blog else {
print("Blog is nil")
return
}
guard let author = blog.author, name = blog.name else {
print("Author or name is nil")
return
}
print("BLOG:")
print(" Author: \(author)")
print(" name: \(name)")
}
此代碼也可以,如果你真的把驚歎號:
struct Blog{
var author:String?
var name: String?
}
func blogInfo2(blog:Blog?){
guard let blog = blog! else {
print("Blog is nil")
return
}
guard let author = blog.author!, name = blog.name! else {
print("Author or name is nil")
return
}
print("BLOG:")
print(" Author: \(author)")
print(" name: \(name)")
}
這是不是有點矛盾或者有人可以清楚地解釋爲什麼不需要感嘆號?
我很驚訝'guard let blog = blog!'版本適合你。你使用的是什麼版本的Swift? –
@PhillipMills是的,現在我意識到在線swift編譯器中嘗試它後,因爲我使用Xcode 8測試版 –