簡體   English   中英

無法將“__NSDictionaryI”類型的值轉換為“NSMutableDictionary”

[英]Could not cast value of type '__NSDictionaryI' to 'NSMutableDictionary'

我最近開始使用 swift。 我正在使用下面的代碼將字符串轉換為 nsmutabledictionary。

print(response);
let responseData = response.data(using: .utf8)!
var json: NSMutableDictionary = try JSONSerialization.jsonObject(with: responseData, options: []) as! NSMutableDictionary;

服務器對請求的響應如下所示。

{"token1":"blah.blah.blah","token_type":"smarty","expires_in":1209600,"token2":"blah.blah.blah"}

我被困在這里。 請幫忙。

這並不奇怪,因為它與 Objective-C 中的行為完全相同。

在 ObjC 中,您不能將不可變類型強制轉換為可變類型。 運行此代碼

NSDictionary *dict = @{@"Foo":@"1"};
NSMutableDictionary *mutableDict = (NSMutableDictionary *)dict;
[mutableDict setObject:@"2" forKey: @"Bar"];

引發異常

-[__NSSingleEntryDictionaryI setObject:forKey:]: 無法識別的選擇器發送到實例

因為類型保持不變。 您必須創建一個新的NSMutableDictionary實例

NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:dict];

具有諷刺意味的是——我仍在談論 ObjC——在NSJSONSerialization的情況下,著名的選項.mutableContainers進來了。使用此選項,您可以直接創建可變數組/字典,請注意,僅在 Objective-C 中。

另一方面,在 Swift 中,此選項無論如何都沒有意義,因為 Swift Dictionary / ArrayNSMutable...對應項彼此不相關,而在var中,您可以簡單地使用 vartable 類型創建一個(

所以寫

var json = try JSONSerialization.jsonObject(with: responseData) as! [String:Any]

底線是:

不要在 Swift 中使用NSMutable...集合類型。

jsonObject(with:options:)返回Any ,您可以嘗試:

let response = """
    {"token1":"blah.blah.blah","token_type":"smarty","expires_in":1209600,"token2":"blah.blah.blah"}
"""
let responseData = response.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: responseData, options: []) as! [String: Any]
let mutableDictionary = NSMutableDictionary(dictionary: json)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM