Removing duplicate elements from an array in Swift

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

    You can always use a Dictionary, because a Dictionary can only hold unique values. For example:

    var arrayOfDates: NSArray = ["15/04/01","15/04/01","15/04/02","15/04/02","15/04/03","15/04/03","15/04/03"]
    
    var datesOnlyDict = NSMutableDictionary()
    var x = Int()
    
    for (x=0;x<(arrayOfDates.count);x++) {
        let date = arrayOfDates[x] as String
        datesOnlyDict.setValue("foo", forKey: date)
    }
    
    let uniqueDatesArray: NSArray = datesOnlyDict.allKeys // uniqueDatesArray = ["15/04/01", "15/04/03", "15/04/02"]
    
    println(uniqueDatesArray.count)  // = 3
    

    As you can see, the resulting array will not always be in 'order'. If you wish to sort/order the Array, add this:

    var sortedArray = sorted(datesOnlyArray) {
    (obj1, obj2) in
    
        let p1 = obj1 as String
        let p2 = obj2 as String
        return p1 < p2
    }
    
    println(sortedArray) // = ["15/04/01", "15/04/02", "15/04/03"]
    

    .

提交回复
热议问题