Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append unique values to an array in swift

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?

like image 600
GuiSoySauce Avatar asked Aug 20 '15 00:08

GuiSoySauce


People also ask

How do you make an array unique 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.

What is reduce in Swift?

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.


1 Answers

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") }
like image 96
Mundi Avatar answered Sep 18 '22 20:09

Mundi