André Luiz André Luiz - 1 year ago 85
Swift Question

Swift 3 - set the key when appending to array

I have this array where I set the keys on the creation. Now in some point in my view I load some more information based on ids (the keys).

var colors = [
"37027" : UIColor(red:150/255, green:57/255, blue:103/255, alpha:1),
"12183" : UIColor(red:234/255, green:234/255, blue:55/255, alpha:1),
"44146" : UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)

I want to add more colors to this array dynamically. How can I insert new items in the array setting the key? Something like

colors["25252"] = UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)

The line above doesn't work, it is just to illustrate what I need.

Thanks for any help

Update: the code above is an example. Below the real code:

var placedBeacons : [BeaconStruct] = []

BeaconModel.fetchBeaconsFromSqlite(completionHandler: {
beacons in

for item in beacons{
self.placedBeacons["\(item.major):\(item.minor)"] = item

Cannot subscript a value of type '[BeaconStruct]' with an index of type String

Answer Source

To match the key subscripting

self.placedBeacons["\(item.major):\(item.minor)"] = item

you have to declare placedBeacons as dictionary rather than an array

var placedBeacons = [String:BeaconStruct]()

It requires that item is of type BeaconStruct

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download