How to get a UIColor from Associative Array in Swift

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 11:37:18

问题


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


回答1:


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




回答2:


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

You could use closestBeacon.minor.integerValue



来源:https://stackoverflow.com/questions/32364062/how-to-get-a-uicolor-from-associative-array-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!