对成员'下标'的模糊引用

Law*_*ris 5 macos swift3

我的代码出错了:

func getBatteryInfos(){
    let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()

    // Pull out a list of power sources
    let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array

    // For each power source...
    for ps in sources {
        // Fetch the information for a given power source out of our snapshot
        let info = IOPSGetPowerSourceDescription(snapshot, ps).takeUnretainedValue() as Dictionary

        // Pull out the capacity
        if let

            capacity = info[kIOPSCurrentCapacityKey] as? Double, //Ambiguous reference to member 'subscript'
             let charging = info[kIOPSIsChargingKey] as? Int{ //Ambiguous reference to member 'subscript'

                batteryPercentage = capacity
                batteryState = charging

                print("Current battery percentage \(batteryPercentage)")
                print("Current state \(batteryState)")



        }
    }
Run Code Online (Sandbox Code Playgroud)

我试图替换info[kIOPSCurrentCapacityKey],info["kIOPSCurrentCapacityKey"]但同样的错误发生.我在StackOverflow上看到了一些关于此错误的问题,但所有答案都不适用于我的代码.

我正在使用Xcode 8 Beta 6和Swift3.在Swift 2中,这段代码完美无缺.

任何帮助表示赞赏:-)

mat*_*att 19

你不能强制转换为无类型的Swift字典或数组.更改

as Dictionary
as Array
Run Code Online (Sandbox Code Playgroud)

as NSDictionary
as NSArray
Run Code Online (Sandbox Code Playgroud)

或者,如果你知道实际的类型(即这是一个数组什么?这是一个字典是什么?),请转向那些实际类型.

另一种方法是使用新的无类型类型,[Any][AnyHashable:Any].但根据我的经验,这可能有点棘手.基本上Apple已经吹走了Objective-C和Swift之间的自动桥接,并将其替换为"宽容拳击",这会导致一些类型的不匹配,你必须自己补偿.