我试图将通用 Array 方法 compactMap
包装在 Array 扩展中,以赋予该方法更多的意义/可读性。我只是想获取一个 Optionals 数组并从中删除所有 nil
值。
extension Array {
public func removeNilElements() -> [Element] {
let noNils = self.compactMap { $0 }
return noNils // nil values still exist
}
}
我遇到的问题是 compactMap
在这里不起作用。 nil
值仍在生成的数组 noNils
中。当我直接使用 compactMap
方法而不使用此包装器时,我得到了没有 nil
值的数组的期望结果。
let buttons = [actionMenuButton, createButton] // [UIBarButtonItem?]
let nonNilButtons = buttons.compactMap { $0 } // works correctly
let nonNilButtons2 = buttons.removeNilElements() // not working
我没有正确设计我的扩展方法吗?
最佳答案
您必须为可选 元素数组定义方法,并将返回类型定义为相应的非可选数组。这可以通过通用函数完成:
extension Array {
public func removingNilElements<T>() -> [T] where Element == T? {
let noNils = self.compactMap { $0 }
return noNils
}
}
例子:
let a = [1, 2, nil, 3, nil, 4] // The type of a is [Int?]
let b = a.removingNilElements() // The type of b is [Int]
print(b) // [1, 2, 3, 4]
在您的代码中,$0
具有(非可选)类型 Element
,它只是被编译器包装成一个可选的,以便匹配的参数类型compactMap()
.
关于swift - 在类扩展中包装泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54261341/