4

我已經Xcode更新到Xcode中8,現在我需要的時候我想轉換的NSDictionary到字典中我只寫了下面在我代碼swift2轉換爲SWIFT 3如何將NSDictionary轉換爲Swift 3中的字典?

let post_paramsValue = post_params as? Dictionary<String,AnyObject?> 

其中post_params是NSDictionary。

但現在隨着SWIFT 3我收到波紋錯誤:

nsdictionary is not convertible to dictionary 

爲什麼呢?什麼改變了?

感謝

EDIT1, 還我已嘗試以下步驟: 讓post_paramsValue = post_params作爲字典

但顯示這個錯誤: enter image description here

EDIT2: 我也試過以下內容:

let post_paramsValue = post_params as Dictionary<String,Any> 

其中我聲明NSDictionary而不是NSDictionary!但它不工作,我得到這個錯誤: enter image description here

EDIT3 還我已嘗試以下步驟:

let post_paramsValue = post_params as Dictionary<String,Any>! 

,但我收到此錯誤: enter image description here

+0

試過嗎? HTTP://計算器。com/questions/31765875/cast-nsdictionary-as-dictionary-swift –

+0

@UmairAfzal感謝您的評論,但爲什麼我需要通過詞典使用循環,這不方便,爲什麼蘋果需要讓事情變得更難? – david

+0

我不知道爲什麼,你試過了嗎?它是否有效? –

回答

8
    Objective-C中的
  • NSDictionary始終爲非可選值。
  • AnyObject斯威夫特3.
  • 考慮兩個率先 「規則」 NSDictionary已成爲Any可橋現澆到Dictionary

let post_paramsValue = post_params as Dictionary<String,Any> 

如果源NSDictionary是可選的,你可以使用as Dictionary<String,Any>?as? Dictionary<String,Any>as! Dictionary<String,Any>as Dictionary<String,Any>!取決於實際類型NSDictionary

+0

謝謝你的回答,但我已經嘗試過,並且它沒有工作,我編輯了問題 – david

+0

然後使用強制轉換運算符'as!',因爲源字典是可選的。 – vadian

+0

再次感謝,爲什麼我不能使用這個:let post_paramsValue = post_params作爲詞典! – david

0

對於那些誰有問題的NSDictionary簡單地擴展

雨燕3.0

extension NSDictionary { 
    var swiftDictionary: Dictionary<String, Any> { 
     var swiftDictionary = Dictionary<String, Any>() 

     for key : Any in self.allKeys { 
      let stringKey = key as! String 
      if let keyValue = self.value(forKey: stringKey){ 
       swiftDictionary[stringKey] = keyValue 
      } 
     } 

     return swiftDictionary 
    } 
} 
相關問題