首页 > 解决方案 > for case let 和 for 循环 + if let 之间有区别吗?

问题描述

我刚刚了解了 for case let,这两个版本的循环具有相同的输出。这让我想知道,for case let 和带有 if-then 语句的普通 for 循环是否有任何区别(在性能或其他方面)?

我开始考虑这个是因为我听说我不应该处理 switch case 和 if-then 相同,可以完成非常不同的事情。

class Daddy {

}

class Son: Daddy {
    func speak() {
        print("I am son!")
    }
}

var people = [Son(), Daddy()]

for case let person as Son in people {
    person.speak()
}

for person in people {
    if let son = person as? Son {
        son.speak()
    }
}

标签: swift

解决方案


正如其他人所评论的那样,代码的性能不是问题。相反,为决策创建一个心理框架才是问题所在。

即,作为程序员,您如何减少大脑将决策引导到代码中所需的时间?你不能让自己每次都自由地做出不同的决定,否则你自己的表现会受到影响。

您做出的任何选择都是可以接受的,但没有决策框架则不行。


我推荐的助记符是思维模式,“我将利用封装样板的语言特性,而不是让自己将样板放入源代码”。这会给你留下:

for case let son as Son in people {
  son.speak()
}

for case let语法是一种基于选项过滤序列的方法。

鉴于这种:

var daddies: [Daddy?] = [Son(), Daddy()]

在这里,爸爸是类型Daddy?

for daddy in daddies {

…但是在这里,它被展开为Daddy

for case let daddy? in daddies {

还有这个……</p>

for person in people {
  if let son = person as? Son {
    son.speak()
  }
}

…只是语法糖:

for person in people {
  if case let son? = person as? Son {
    son.speak()
  }
}

演示将 if 语句提升到 for 循环(这是它的正确范围)的中间步骤将无法编译......</p>

for case let son? as? Son in people {

…所以相反,你必须直接跳到

for case let son as Son in people {

这与 switch 语句使用的语法糖相同,也不允许条件转换。


推荐阅读