swift guard用法

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)")

}

}

猜你喜欢

转载自blog.csdn.net/asuno_1/article/details/80582325