我了解选项的使用足以知道何时需要使用感叹号解开选项。为什么警卫语句中不需要感叹号?
此代码可以工作和编译,但不使用感叹号:
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)")
}
这不是有点矛盾,还是有人可以清楚地解释为什么不需要感叹号?