简体   繁体   中英

How to get a UIColor from Associative Array in Swift

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

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

You could use closestBeacon.minor.integerValue

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM