【发布时间】:2016-07-18 10:14:10
【问题描述】:
我一直在尝试从字符串数组中提取非零值。如下所示。但是,我的前辈希望它也能够从其他类型中提取非零值。
我读过,泛型可以帮助我处理不同的类型。如何使用泛型,以便我可以使用以下类似扩展来处理其他类型?
getNonNil 必须返回提取的特定类型的非零值(即如果数组是 [String?] 它必须返回 [String],如果 [Int?] 则返回 [Int] )
因为我必须做进一步的计算。
我尝试过的如下:
import Foundation
// Extended the collection-type so that collectiontype is constrained to having element with optional strings
extension CollectionType where Self.Generator.Element == Optional<String>{
func getNonNil() -> [String] {
// filter out all nil elements and forcefully unwrap them using map
return self.filter({$0 != nil}).map({$0!})
}
}
// Usage
let x: [String?] = ["Er", "Err", nil, "errr"]
x.getNonNil().forEach { (str) in
print(str)
}
【问题讨论】:
标签: ios swift generics optional