How to make generics in collection type constraint?

后端 未结 3 980
执笔经年
执笔经年 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:20

    The easiest approach is using flatMap as kennytm suggested, but if you absolutely want to know how to create such a method using generics, one approach would be to create a global method that takes in the collection as a parameter:

    public func getNonNil>(collection: C) -> [T] {
        return collection.filter({$0 != nil}).map({$0!})
    }
    
    let x: [String?] = ["Er", "Err", nil, "errr"]
    
    print(getNonNil(x)) // returns ["Er", "Err", "errr"]
    

提交回复
热议问题