Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous reference to member 'subscript'

Tags:

macos

swift3

I got this error on 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 to replace info[kIOPSCurrentCapacityKey] with info["kIOPSCurrentCapacityKey"] but the same error occurs. I saw a few questions about this error on StackOverflow but all the answers are not working with my code.

I'm working with Xcode 8 Beta 6 and Swift3. In Swift 2, this code worked perfectly.

Any help is appreciated :-)

like image 728
Lawris Avatar asked Aug 24 '16 18:08

Lawris


1 Answers

You cannot cast to a typeless Swift dictionary or array. Change

as Dictionary
as Array

to

as NSDictionary
as NSArray

Or, if you know the actual types (i.e. what is this an array of? what is this a dictionary of?), cast down to those actual types.

Another approach is to use the new untyped types, [Any] and [AnyHashable:Any]. But this can be a little tricky, in my experience. Basically Apple has blown away the automatic bridging between Objective-C and Swift and replaced it with "permissive boxing", and this causes some type mismatches that you have to compensate for yourself.

like image 51
matt Avatar answered Nov 11 '22 04:11

matt