Removing duplicate elements from an array in Swift

后端 未结 30 2012
遥遥无期
遥遥无期 2020-11-22 00:07

I might have an array that looks like the following:

[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]

Or, reall

30条回答
  •  不思量自难忘°
    2020-11-22 00:53

    edit/update Swift 4 or later

    We can also extend RangeReplaceableCollection protocol to allow it to be used with StringProtocol types as well:

    extension RangeReplaceableCollection where Element: Hashable {
        var orderedSet: Self {
            var set = Set()
            return filter { set.insert($0).inserted }
        }
        mutating func removeDuplicates() {
            var set = Set()
            removeAll { !set.insert($0).inserted }
        }
    }
    

    let integers = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
    let integersOrderedSet = integers.orderedSet // [1, 4, 2, 6, 24, 15, 60]
    

    "abcdefabcghi".orderedSet  // "abcdefghi"
    "abcdefabcghi".dropFirst(3).orderedSet // "defabcghi"
    

    Mutating method:

    var string = "abcdefabcghi"
    string.removeDuplicates() 
    string  //  "abcdefghi"
    
    var substring = "abcdefabcdefghi".dropFirst(3)  // "defabcdefghi"
    substring.removeDuplicates()
    substring   // "defabcghi"
    

    For Swift 3 click here

提交回复
热议问题