不能下标类型的值' [Int:UIColor]'索引类型' NSNumber'

时间:2016-04-19 09:43:28

标签: ios swift ibeacon

美好的一天。我试图按照本教程https://www.youtube.com/watch?v=3jJiqzbzutU进行此错误消息无法下标类型' [Int:UIColor]'索引类型为NSNumber。我做了他在教程中做的同样的事情,这出错了。请帮忙。错误来自这行代码

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

这是我的代码供参考。

class ViewController: UIViewController, CLLocationManagerDelegate {

let locationManager = CLLocationManager()
let region1 = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "myuuidString")!, identifier: "skybeacon1")

let colors = [2: UIColor.redColor(), 1: UIColor.blueColor()]

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self

    if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse {
        locationManager.requestWhenInUseAuthorization()
    }
    locationManager.startRangingBeaconsInRegion(region1)
}

func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], 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.major]
    }
}
}

3 个答案:

答案 0 :(得分:0)

CLBeacon.major是一个返回NSNumber的属性。只需使用closestBeacon.major.integerValue

即可

答案 1 :(得分:0)

NSNumberInt不同但相关,只是投了它(不是强制的)

let closestBeacon = knownBeacons[0] // as CLBeacon is not needed, the compiler knows the type
self.view.backgroundColor = self.colors[closestBeacon.major as Int] 

答案 2 :(得分:0)

你好如果你在swift 4中编程,请使用:

closestBeacon.major.intValue

而不是

closestBeacon.major.integerValue