Search code examples
swiftparse-platformios8xcode6uipickerview

How to remove duplicate data in the UIPickerView in Swift


As you can see the picture I've uploaded, the Picker View having the duplicate data

May I know how to remove the duplicate data which all the data is passing from the Parse database. I just select one column and pass that column data to this picker view. I've try to find the query.wherekey but it didn't have the DISTINCT function which similar to the SQL statement, so what should I do to avoid the data duplication?


Solution

  • As you add items one by one into your self.pickerString array, just verify if this array contains or not the new value before addObject new value to the array. For example:

    if !self.pickerString.contains(object["Intake"] as! String) {
         self.pickerString.append(object["Intake"] as! String)
    }
    

    There is no built-in function to remove duplicate items in an array in swift (correct me if I'm wrong). However, you can add new features for array with 'extension' keyword:

    extension Array {
        func distinct<T: Equatable>() -> [T] {
            var newArray = [T]()
            for item in self {
                if !contains(newArray, item as! T) {
                    newArray.append(item as! T)
                }
            }
            return newArray
        }
    }
    

    usage:

    let s = ["344","333","1","2","333"]
    var p = s.distinct() as [String]