Removing duplicate elements from an array in Swift

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

    swift 2

    with uniq function answer:

    func uniq(source: S) -> [E] {
        var seen: [E:Bool] = [:]
        return source.filter({ (v) -> Bool in
            return seen.updateValue(true, forKey: v) == nil
        })
    }
    

    use:

    var test = [1,2,3,4,5,6,7,8,9,9,9,9,9,9]
    print(uniq(test)) //1,2,3,4,5,6,7,8,9
    

提交回复
热议问题