2016-08-24 41 views
5

我得到了我的代碼此錯誤:曖昧參考成員「下標」

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中,這段代碼完美運行。

任何幫助表示讚賞:-)

回答

19

不能轉換爲無類型斯威夫特字典或陣列。更改

as Dictionary 
as Array 

as NSDictionary 
as NSArray 

或者,如果你知道實際的類型(即這是什麼一個數組的什麼?這是一本字典的?),垂下來的實際類型。

另一種方法是使用新的非類型,[Any][AnyHashable:Any]。但根據我的經驗,這可能有點棘手。基本上,Apple已經吹走了Objective-C和Swift之間的自動橋接,並用「寬容拳擊」取而代之,這會導致一些類型不匹配,你必須補償自己。

+0

我不能對此進行測試因爲我不知道你使用的類型(例如,我不知道IOPSCopyPowerSourcesInfo是什麼),所以你將不得不實驗t並可能調整以獲得正確的結果。例如,你可能需要'as!'而不是'as'。 – matt

+0

非常感謝,在Dictionary和Array之前添加了NS後就成功了。你認爲蘋果爲了更高的精度和安全性而打破了自動橋接嗎? – Lawris

+1

你可以得出你自己的結論。 :) https://github.com/apple/swift-evolution/blob/master/proposals/0072-eliminate-implicit-bridging-conversions.md – matt

0

我發現這個

我有同樣的問題

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

然後我加入詞典的更具體的類型

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

它的作品對我來說