swift Guard语法

本文介绍了 Swift 中 guard 语句的基本用法及其优势。guard 语句用于在条件不满足时优雅地退出函数,避免了多层 if 嵌套造成的逻辑混乱,并能清晰直观地展示代码逻辑。此外,文章还对比了使用 if-let 和 guard let 的两种情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//swift guard语句

/*

if语句相同的是,guard也是基于一个表达式的布尔值去判断一段代码是否该被执行。与if语句不同的是,guard只有在条件不满足的时候才会执行这段代码。你可以把guard近似的看做是Assert,但是你可以优雅的退出而非崩溃。

是对你所期望的条件做检查,而非不符合你期望的。又是和assert很相似。如果条件不符合,guardelse语句就运行,从而退出这个函数。

如果通过了条件判断,可选类型的变量在guard语句被调用的范围内会被自动的拆包 -这个例子中该范围是fooGuard函数内部。这是一个很重要,却有点奇怪的特性,但让guard语句十分实用。

对你所不期望的情况早做检查,使得你写的函数更易读,更易维护。

*/


func fooNonOptionalGood(x:Int) ->Bool{

    guard x > 0else {

        //执行不满足条件时的操作

        print("x<=0,不满足条件退出")

        return false

    }

    

    print("x > 0,x的值是:\(x)")

    return true

    

}


fooNonOptionalGood(5)

fooNonOptionalGood(-2)


//guard demo2

guard优点

1、代码清爽直观。

2、不必再ifif,会混淆你的逻辑。

3if let name = person["name"]{}其中name的作用域仅局限于紧随的大括号中,而guard let name = person["name"]范围更广!


//使用if-let解包

func greet_if(person:[String:String]) {

    if let name = person["name"] {

        print("输入name:Hello\(name)")//名字存在

        

        if let location = person["location"] {

            print("输入location:I hope the weather is nice in\(location)")

        } else {

            print("location未输入:I hope the weather is nice near you")

            return;

        }

    } else {

        print("没输入名字直接退出")

        return;

    }

}

greet_if(["name":"json","location":"NewYork"])

greet_if(["name":"json"])

greet_if(["location":"NewYork"])


//使用guard改写

func greet_guard (person:[String:String]) {

    guard let name = person["name"]else {

        print("没输入名字直接退出")

        return;

    }

    print("输入name:Hello\(name)")//名字存在

    guard let location = person["location"]else{

        print("location未输入:I hope the weather is nice near you")

        return;

    }

    print("输入location:I hope the weather is nice in\(location)")

}

greet_guard(["name":"json","location":"NewYork"])

greet_guard(["name":"json"])

greet_guard(["location":"NewYork"])


/*

执行结果:

输入name:Hello json

输入location:I hope the weather is nice in NewYork

输入name:Hello json

location 未输入:I hope the weather is nice near you

没输入名字直接退出

*/




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值