swift - 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()
}
}
解决方案
正如其他人所评论的那样,代码的性能不是问题。相反,为决策创建一个心理框架才是问题所在。
即,作为程序员,您如何减少大脑将决策引导到代码中所需的时间?你不能让自己每次都自由地做出不同的决定,否则你自己的表现会受到影响。
您做出的任何选择都是可以接受的,但没有决策框架则不行。
我推荐的助记符是思维模式,“我将利用封装样板的语言特性,而不是让自己将样板放入源代码”。这会给你留下:
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 语句使用的语法糖相同,也不允许条件转换。
推荐阅读
- angularjs - 如何在模块化 angularjs 范围内测试指令?
- c# - 我如何模拟 TryValidateModel
- openrefine - 有没有办法强制 Open Refine 将所有历史更改提取到 JSON 中
- python-3.x - 登录会话每隔几秒就会过期
- wordpress - Woocommerce 订阅使用 REST API 处理更新
- c++ - 类模板参数的特化在 GCC、Clang 和 MSVC 中编译,但 GCC 选择了另一种特化
- c# - 如何在注册表页面上列出身份中的角色
- flutter - 导航到另一个屏幕时我丢失了流数据
- java - 如何从 xml java android 读取所有标签和值?
- jquery - 仅发送第一个输入值的输入字段数组