创建一个扩展,从斯威夫特数组过滤尼尔斯 [英] Creating an extension to filter nils from an Array in Swift
问题描述
我试图写一个扩展阵列,这将使可选T的数组转化成非可选T的数组。
I'm trying to write an extension to Array which will allow an array of optional T's to be transformed into an array of non-optional T's.
例如。这可以写成这样的免费功能:
e.g. this could be written as a free function like this:
func removeAllNils(array: [T?]) -> [T] {
return array
.filter({ $0 != nil }) // remove nils, still a [T?]
.map({ $0! }) // convert each element from a T? to a T
}
但是,我不能得到这个作为一个扩展工作。我想告诉大家,扩展只适用于可选值的数组的编译器。这是我到目前为止有:
But, I can't get this to work as an extension. I'm trying to tell the compiler that the extension only applies to Arrays of optional values. This is what I have so far:
extension Array {
func filterNils<U, T: Optional<U>>() -> [U] {
return filter({ $0 != nil }).map({ $0! })
}
}
(它不编译!)
推荐答案
这是不可能限制一个通用的结构或类中定义的类型 - 阵列设计与任何类型的工作,所以你不能添加一个可行的方法为一个类型的子集。只能指定类型的约束声明泛型类型时
It's not possible to restrict the type defined for a generic struct or class - the array is designed to work with any type, so you cannot add a method that works for a subset of types. Type constraints can only be specified when declaring the generic type
只有这样,才能实现你需要的是通过创建为全局函数或静态方法 - 在后一种情况:
The only way to achieve what you need is by creating either a global function or a static method - in the latter case:
extension Array {
static func filterNils(array: [T?]) -> [T] {
return array.filter { $0 != nil }.map { $0! }
}
}
var array:[Int?] = [1, nil, 2, 3, nil]
Array.filterNils(array)
这篇关于创建一个扩展,从斯威夫特数组过滤尼尔斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!