I might have an array that looks like the following:
[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
Or, reall
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