Bal*_*ody 5 arrays generics swift option-type
我想创建一个数组扩展,其中数组的元素是可选的,方法的返回类型是非可选的元素类型。
是否可能,如果可以,语法是什么?
主要思想是伪代码:
extension Array where Element: Optional {
func foo() -> ReturnType<Wrapped<Element>> {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定你的意思,Wrapped<Element>但既然你需要返回一些东西,为什么不使用闭包作为返回值,就像这个函数来获取特定索引处的元素
extension Array {
func value<T>(at index: Int, emptyAction: () -> T) -> T where Element == T? {
if let value = self[index] {
return value
}
return emptyAction()
}
}
Run Code Online (Sandbox Code Playgroud)
例子
var test = [String?]()
test.append("ABC")
test.append("DEF")
test.append(nil)
for i in 0..<test.count {
print(test.value(at: i, emptyAction: { "<empty>" }))
}
Run Code Online (Sandbox Code Playgroud)
输出
ABC
DEF
<empty>
Run Code Online (Sandbox Code Playgroud)