ios - How to make generics in collection type constraint? -
i have been trying extract non-nil values string array. below. but, senior wants able extract non-nil values other types too.
i read, generics me handling different types. how can use generics use following extension work other types too?
getnonnil
must return extracted non-nil values of specific type (i.e. if array [string?] must return [string], returns [int] if [int?])
because have further calculations.
what have tried below:
import foundation // extended collection-type collectiontype constrained having element optional strings extension collectiontype self.generator.element == optional<string>{ func getnonnil() -> [string] { // filter out nil elements , 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) }
for getnonnil
use
x.flatmap { $0 } // returns ["er", "err", "errr"] [string]
for original question, typically introduce protocol optional type (e.g. via muukii/optionalprotocol package):
protocol optionalprotocol { associatedtype wrapped var value: wrapped? { } } extension optional: optionalprotocol { public var value: wrapped? { return self } } extension collectiontype self.generator.element: optionalprotocol { func getnonnil() -> [self.generator.element.wrapped] { ... } }
Comments
Post a Comment