2016-09-07 107 views
1

我想將swift數組字典傳遞給NSMutableArray。但是我收到錯誤「無法將類型[[String:Anyobject?]]的值轉換爲期望的參數類型NSMutableArray」。以下是代碼:Swift將字典數組傳遞給NSMutableArray

var ary : [[String:AnyObject?]] = [] 
    var mutableDictionary = [String: AnyObject?]() 

    for c in buffer { 
     mutableDictionary.updateValue(c.Name, forKey: "name") 
     mutableDictionary.updateValue(c.Number, forKey: "phoneNumber") 
     mutableDictionary.updateValue(c.id, forKey: "id") 
     ary.append(mutableDictionary) 
    } 

現在將這個「ary」作爲NSMutableArray傳遞給Objective C方法!

Manager.sharedInstance().List(ary) 
+0

嘗試'Manager.sharedInstance()。List(ary as!NSMutableArray)'。 – Avi

+0

不,它會崩潰,因爲從[[string:anyobject?]]投射到nsmutablearray總是失敗 – Hitesh

+0

'NSMutableDictionary'不能包含optionals,也不能包含'NSMutableArray'。你必須在'AnyObject'上放下可選項。 – Avi

回答

2

副本:

var ary : [[String:AnyObject]] = [] 
    var mutableDictionary = [String: AnyObject]() 
    var mutableArray:NSMutableArray! 

    for _ in 0...4 { 
     mutableDictionary.updateValue("adsf", forKey: "name") 
     mutableDictionary.updateValue("dsf", forKey: "phoneNumber") 
     mutableDictionary.updateValue("sdfd", forKey: "id") 
     ary.append(mutableDictionary) 
    } 

    mutableArray = NSMutableArray(array: ary) 

卸下可選的伎倆!

+0

非常感謝!工作,但它會導致可選的問題? anyidea – Hitesh

+0

我唯一的解釋是:_「NSMutableArray不包含可選項」_。我希望有更好更深刻的解釋的人會在這裏解釋我們。 –

+0

太棒了!謝謝! :) – Hitesh

1

//嘗試像你的問題的這種

Manager.sharedInstance().List(NSMutableArray(array: ary as! NSArray)) 
+0

不,它會崩潰,因爲從[[string:anyobject?]]投射到nsmutablearray總是失敗 – Hitesh

+0

做一件事而不是此語句(var ary:[[String:AnyObject?]] = [])可以像這樣var ary:[AnyObject] = [] –

+0

並嘗試以上解決方案 –