gpt4 book ai didi

ios - guard 和 invert if 有什么区别

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:28 24 4
gpt4 key购买 nike

抱歉,如果这是一个菜鸟问题,因为我是 Swift 的新手,无法从 Google 找到这个答案。

当我第一次看到 guard 时,我想到了其他编程语言中的 invert if

var optString: String?
guard optString != nil else { return }
if optString == nil { return }

第二行和第三行不是产生相同的结果吗?

我可以理解 if let 使代码比检查 nil 并展开它更简单,但是 guard 的目的是什么?根据我的研究,我只能发现有人说它可以减少嵌套的 if 而反转 if 可以做同样的事情。

EDIT: I am asking about invert if NOT if let. Please read the question before flagging it.

最佳答案

guard 有两个重要的事情是 if(或 if let)没有的:

  • guard 必须有 else 子句,该子句必须有 return 语句或其他离开守卫父作用域的方式(例如 throw break)。
  • guard 声明和分配的变量在 guard 的父范围内可用。

guard 的全部要点在于它允许您避免繁琐的构造,例如 if let 主体继续到方法的末尾,因为代码必须仅在某些情况下执行可选的解包成功。基本上,这是实现提前退出的一种更简洁的方法。

所以,为了回答你的直接问题,是的 guard optString != nil else { return } 等同于 if optString == nil { return } ,但事实并非如此引入 guard 的目的是什么:

Using a guard statement for requirements improves the readability of your code, compared to doing the same check with an if statement. It lets you write the code that’s typically executed without wrapping it in an else block, and it lets you keep the code that handles a violated requirement next to the requirement.

来源:Apple's documentation .

关于ios - guard 和 invert if 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37986322/

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