我的代码中出现此错误:
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)")
}
}
我尝试用替换info[kIOPSCurrentCapacityKey]
,info["kIOPSCurrentCapacityKey"]
但发生相同的错误。我在StackOverflow上看到有关此错误的几个问题,但所有答案均不适用于我的代码。
我正在使用Xcode 8 Beta 6和Swift3。在Swift 2中,此代码运行完美。
任何帮助表示赞赏:-)
您不能转换为无类型的Swift字典或数组。改变
as Dictionary
as Array
到
as NSDictionary
as NSArray
或者,如果你知道实际的类型(即这是什么一个数组的?这是什么字典的?),垂下来的实际类型。
另一种方法是使用新的未类型化类型[Any]
和[AnyHashable:Any]
。但是,根据我的经验,这可能会有些棘手。基本上,Apple吹灭了Objective-C和Swift之间的自动桥接功能,并用“宽容拳击”代替了它,这会导致某些类型的不匹配,您必须自己补偿。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句