I haven't found anything on that in Swift. Have found how to find unique values on an array, but not this. Sorry if it sounds quite basic...
But I have the following array
var selectedValues = [String]()
And the following value that comes from a Parse query
var objectToAppend = object.objectForKey("description")! as! String
this is how I'am doing it at the moment.
self.selectedHobbies.append(objectToAppend)
But because the query happens repeated times, it ends up appending repeated values. It works, but I just want to not waste memory and only keep unique values.
Any ideas on how to solve that in swift?
Use a dictionary like var unique = [<yourtype>:Bool]() and fill in the values like unique[<array value>] = true in a loop. Now unique.
Swift version: 5.6. The reduce() method iterates over all items in array, combining them together somehow until you end up with a single value.
You can use a Set
which guarantees unique values.
var selectedValues = Set<String>()
// ...
selectedValues.insert(newString) // will do nothing if value exists
Of course, the elements of a Set
are not ordered.
If you want to keep the order, just continue with the Array
but check before you insert.
if !selectedValues.contains("Bar") { selectedValues.append("Bar") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With