gpt4 book ai didi

swift - 如何在 swift 中使用 guard 而不是 if

转载 作者:搜寻专家 更新时间:2023-11-01 05:50:30 24 4
gpt4 key购买 nike

如何在 swift 中使用“守卫”。我已经阅读了很多关于“守卫”的文章。但是我对此没有清楚的了解。请给我明确的想法。请给我以下“if”语句的示例输出。

if firstName != "" 
{
if lastName != ""
{
if address != ""
{
// do great code
}
}
}

最佳答案

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

func doSomething(data: String?) -> String {

// If data is nil, then return
guard let data = data else { return "Invalid data" }

defer { print("This will always be printed if data isn't nil") }

// data is now a non optional String
if data.lowercaseString == "ok" { return "Data is \"ok\"" }

return "I'm your father"
}

print(doSomething("ok"))

输出:

This will always be returned if data isn't nil
Data is "ok"

更多关于你的问题:

The value of any condition in a guard statement must have a type that conforms to the BooleanType protocol.

func doSomething(data: String) -> String {

guard !data.isEmpty else { return "Data is empty" }

return data
}

print(doSomething("ok")) // ok
print(doSomething("")) // Data is empty

关于swift - 如何在 swift 中使用 guard 而不是 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36370513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com