【问题标题】:Cannot subscript a value of type '[Int : UIColor]' with an index of type 'NSNumber'无法使用“NSNumber”类型的索引为“[Int : UIColor]”类型的值下标
【发布时间】:2016-04-19 09:43:27
【问题描述】:

美好的一天。我试图遵循本教程https://www.youtube.com/watch?v=3jJiqzbzutU 并收到此错误消息无法使用NSNumber 类型的索引来下标“[Int:UIColor]”类型的值。我做了他在教程中做的同样的事情,结果出错了。请帮忙。错误来自这行代码

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]
    }
}
}

【问题讨论】:

  • closestBeacon.majorNSNumber。你想要一个int self.colors[myInt]。所以你需要将closestBeacon.major 转换为int

标签: ios swift ibeacon


【解决方案1】:

您好,如果您使用 swift 4 进行编程,请使用:

closestBeacon.major.intValue

而不是

closestBeacon.major.integerValue

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这个修复了它与最接近的Beacon.major 相同的Int。非常感谢。
    【解决方案3】:

    NSNumberInt 不同但相关,只需强制转换即可(非强制)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多