Unable to use contains within a Swift Array extension

前端 未结 4 712
故里飘歌
故里飘歌 2020-12-03 15:12

I am trying to write a simple Array extension that provides a \'distinct\' method. Here is what I have so far:

extension Array {
  func distinct() -> T[]          


        
4条回答
  •  孤城傲影
    2020-12-03 15:41

    Finally found out how to do it:

    extension Array {
        func contains(obj: T) -> Bool {
            return self.filter({$0 as? T == obj}).count > 0
        }
    
        func distinct(_: T) -> T[] {
            var rtn = T[]()
    
            for x in self {
                if !rtn.contains(x as T) {
                    rtn += x as T
                }
            }
    
            return rtn
        }
    }
    

    And usage/testing:

    let a = [ 0, 1, 2, 3, 4, 5, 6, 1, 2, 3 ]
    
    a.contains(0)
    a.contains(99)
    
    a.distinct(0)
    

    Unfortunately, I can't figure out a way to do it without having to specify an argument which is subsequently ignored. The only reason it's there is to invoke the correct form of distinct. The major advantage of this approach for distinct seems to be that it's not dumping a common term like distinct into the global namespace. For the contains case it does seem more natural.

提交回复
热议问题