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

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容