How to get a UIColor from Associative Array in Swi

2019-08-10 19:43发布

I have this array with some UIColors:

let colors = [
    35302: UIColor(red: 66/255, green: 55/255, blue: 101/255, alpha: 1),
    53350: UIColor(red: 158/255, green: 218/255, blue: 222/255, alpha: 1),
    54747: UIColor(red: 158/255, green: 222/255, blue: 189/255, alpha: 1)
]

Now, I'm trying to access some index in Array:

func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
    let knownBeacons = beacons.filter{ $0.proximity != CLProximity.Unknown }
    if(knownBeacons.count > 0) {
        let closestBeacon = knownBeacons[0] as! CLBeacon
        self.view.backgroundColor = self.colors[closestBeacon.minor]
    }
}

The line:

self.view.backgroundColor = self.colors[closestBeacon.minor]

I'm getting this error:

Cannot subscript a value of type '[Int: UIColor]' with an index of type 'NSNumber'

I'm trying to make a HelloWorld with my new Beacons and I'm stuck in this part. I would like to understand how this really work.

Thanks

2条回答
叛逆
2楼-- · 2019-08-10 19:49

You use NSNumber but array requires Int as index. Choose one of the following:

self.view.backgroundColor = self.colors[closestBeacon.minor as Int]
self.view.backgroundColor = self.colors[closestBeacon.minor.integerValue]
self.view.backgroundColor = self.colors[Int(closestBeacon.minor)]

You could also check this question Swift convert object that is NSNumber to Double

查看更多
趁早两清
3楼-- · 2019-08-10 20:11

By the looks of things, closestBeacon.minor is an NSNumber, while colors are indexed by Int.

You could use closestBeacon.minor.integerValue

查看更多
登录 后发表回答