我一直在尝试从字符串数组中提取非零值。如下图。但是,我的学长希望它也能够从其他类型中提取非 nil 值。
我读到,泛型 可以帮助我处理不同的类型。我怎样才能使用泛型,以便我也可以使用以下类似扩展来处理其他类型?
getNonNil
必须返回提取的特定类型的非 nil 值(即 如果数组是 [String?],它必须返回 [String],如果 [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)
}
最佳答案
对于 getNonNil
你可以简单地使用
x.flatMap { $0 }
// returns ["Er", "Err", "errr"] which is [String]
对于最初的问题,通常您可以为 Optional 类型引入一个协议(protocol)(例如通过 muukii/OptionalProtocol 包):
protocol OptionalProtocol {
associatedtype Wrapped
var value: Wrapped? { get }
}
extension Optional: OptionalProtocol {
public var value: Wrapped? { return self }
}
extension CollectionType where Self.Generator.Element: OptionalProtocol {
func getNonNil() -> [Self.Generator.Element.Wrapped] {
...
}
}
关于ios - 如何在集合类型约束中制作泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38434125/