Unable to use contains within a Swift Array extension

前端 未结 4 713
故里飘歌
故里飘歌 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:34

    Swift 1.x

    The elements in an array don't have to be Equatable, i.e. they don't have be comparable with ==.

    That means you can't write that function for all possible Arrays. And Swift doesn't allow you to extend just a subset of Arrays.

    That means you should write it as a separate function (and that's probably why contains isn't a method, either).

    let array = ["a", "b", "c", "a"]
    
    func distinct(array: [T]) -> [T] {
        var rtn = [T]()
    
        for x in array {
            var containsItem = contains(rtn, x)
            if !containsItem {
                rtn.append(x)
            }
        }
        return rtn
    }
    
    distinct(array) // ["a", "b", "c"]
    

    Update for Swift 2/Xcode 7 (Beta)

    Swift 2 supports restricting extensions to a subset of protocol implementations, so the following is now allowed:

    let array = ["a", "b", "c", "a"]
    
    extension SequenceType where Generator.Element: Comparable {
        func distinct() -> [Generator.Element] {
            var rtn: [Generator.Element] = []
    
            for x in self {
                if !rtn.contains(x) {
                    rtn.append(x)
                }
            }
            return rtn
        }
    }
    
    array.distinct() // ["a", "b", "c"]
    

    Note how apple added SequenceType.contains using the same syntax.

提交回复
热议问题