Removing duplicate elements from an array in Swift

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

    You can use directly a set collection to remove duplicate, then cast it back to an array

    var myArray = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
    var mySet = Set(myArray)
    
    myArray = Array(mySet) // [2, 4, 60, 6, 15, 24, 1]
    

    Then you can order your array as you want

    myArray.sort{$0 < $1} // [1, 2, 4, 6, 15, 24, 60]
    

提交回复
热议问题