Removing duplicate elements from an array in Swift

后端 未结 30 2149
遥遥无期
遥遥无期 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:35

    An alternate (if not optimal) solution from here using immutable types rather than variables:

    func deleteDuplicates(seq:S)-> S {
        let s = reduce(seq, S()){
            ac, x in contains(ac,x) ? ac : ac + [x]
        }
        return s
    }
    

    Included to contrast Jean-Pillippe's imperative approach with a functional approach.

    As a bonus this function works with strings as well as arrays!

    Edit: This answer was written in 2014 for Swift 1.0 (before Set was available in Swift). It doesn't require Hashable conformance & runs in quadratic time.

提交回复
热议问题