Ambiguous reference to member index '

I got this error in my code:

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)") } } 

I tried replacing info[kIOPSCurrentCapacityKey] with info["kIOPSCurrentCapacityKey"] , but the same error. I saw several questions about this error in StackOverflow, but all the answers do not work with my code.

I work with Xcode 8 Beta 6 and Swift3. In Swift 2, this code worked fine.

Any help is appreciated :-)

+5
source share
2 answers

You cannot overlay an unlimited Swift dictionary or array. The change

 as Dictionary as Array 

to

 as NSDictionary as NSArray 

Or, if you know the actual types (i.e. what kind of array is this? What kind of dictionary is this?), They are reset to these actual types.

Another approach is to use the new untyped types [Any] and [AnyHashable:Any] . But it can be a little complicated, in my experience. Basically, Apple has blown away the automatic switch between Objective-C and Swift and replaced it with an β€œallow box”, and this causes some type mismatches that you must compensate for yourself.

+19
source

I found this

I have the same problem

  if let paymentDict = dict["payment"] as? Dictionary { self.payment = OrderPayment(dict: paymentDict) } 

then I add a more specific type of dictionary

  if let paymentDict = dict["payment"] as? Dictionary<String,AnyObject> { self.payment = OrderPayment(dict: paymentDict) } 

It works for me

0
source

All Articles