swift - 在 Array.first 中隐式展开选项
问题描述
回想一下Array
'sfirst
方法返回一个可选项。下面给出了一个警告,它隐式地强制了可选,所以大概这是不好的做法:
let names = ["Bob", "Alice"]
let x = names.first
print(x)
// Warning: Expression implicitly coerced from 'String?' to 'Any'
然而,在 Apple Swift 文档中对闭包的示例进行了简化,这看起来是等效的,并且不会引发任何警告。
var closures: [() -> Void] = []
closures.append {print("Hello from the first closure in the list!")}
closures.append {print("Hello from the second closure in the list!")}
// Implicitly coerce the closure
closures.first?()
// Printed: Hello from the first closure in the list!
除了一个是可选字符串而另一个是可选闭包这一事实之外,这些难道不是“相同的”吗?因为它在官方 Swift 文档中并且不会引发任何错误,所以我被引导相信这是一个不错的用法。我错过了什么?
编辑:感谢您的回复!我想我现在明白了。与第一个类似的示例更像是:
var closures: [() -> String] = []
closures.append {"Hello from the first closure in the list!"}
print(closures.first?())
这确实给出了同样的警告,因为即使闭包没有,可选链接也会返回一个可选的。
解决方案
推荐阅读
- visual-studio - 如何使用 dotnet watch run 调试 dockerised .net core 应用程序
- javascript - 使用“fs”读取 JSON 文件会抛出“invalid json”Node.js
- twilio - Twilio:不想保留语音呼叫者号码的日志
- r - 安装包时 R 中的错误:shiny 或 java_home 的问题?是因为opensteetmap吗?
- python - 有没有办法直接告诉我的 python 程序将鼠标与 os.system("import filename.png") 一起使用?
- r - 按条件填充晶格散点图中的圆圈
- excel - 可以显示具有相同名称并引用相同宏/vba 代码的相同对象(显示菜单的文本框)吗?
- java - 总结两个测验的分数并显示到菜单中
- latex - 如何在表格中添加垂直线?
- json - 无法将 json 转换为 csv