How to make generics in collection type constraint?

后端 未结 3 978
执笔经年
执笔经年 2020-12-04 03:04

I have been trying to extract non-nil values from the String array. Like below. But, my senior wants it to be able to extract non-nil values from other type

3条回答
  •  情话喂你
    2020-12-04 03:24

    For getNonNil you could simply use

    x.flatMap { $0 }
    // returns ["Er", "Err", "errr"] which is [String]
    

    For the original question, typically you could introduce a protocol to the Optional type (e.g. via the muukii/OptionalProtocol package):

    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] {
            ...
        }
    }
    

提交回复
热议问题