guard語句是swift 2 之後新添加的關鍵字,與if語句非常類似,可以在判斷一個條件爲true的情況下執行某語句,否則終止或跳過執行某語句。他設計的目的是替換複雜if-else語句的嵌套,提高成虛的可讀性。
guard 條件表達式 else {
跳轉語句
}
語句組
主要用於嵌套判斷
列:
//創建結構體
class guardCode: NSObject {
struct Blog{
let name:String?
let URL:String?
let author:String?
}
func ifCode(blog:Blog)
{
//if 語句嵌套判斷
if let blogName = blog.name
{
print("這篇博客的名字是\(blog.name)")
if let blogURL = blog.URL{
print("這篇博客的地址是\(blog.URL)")
if let blogAuthour = blog.author {
print("這篇博客的作者是\(blog.author)")
}
else
{
print("這篇博客沒有作者")
}
}
else{
print("博客沒有地址")
}
}
else{
print("這篇博客沒有名字")
}
}
func guradCode(blog:Blog)
{
//guard 語句嵌套判斷
guard let name = blog.name else {
print("這篇博客沒有名字")
return
}
print("這篇博客的名字是\(blog.name)")
guard let URL = blog.URL else {
print("這篇博客沒有名字")
return
}
print("博客沒有地址")
guard let author = blog.author else {
print("這篇博客沒有作者")
return
}
print("這篇博客的作者是\(blog.author)")
}
}