首页 > 解决方案 > 在 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?())

这确实给出了同样的警告,因为即使闭包没有,可选链接也会返回一个可选的。

标签: swift

解决方案


推荐阅读