2015-09-29 86 views
0

由於升級到Xcode7,我收到以下錯誤:斯威夫特 - 無法調用初始化類型「的NSDictionary」

Cannot invoke initializer for type 'NSDictionary' with an argument list of type '(objects: [AnyObject!], forKeys: [String])' 

在這行代碼:

self.sessionBids!.addObject(NSDictionary(objects: [PFUser.currentUser().objectId, PFUser.currentUser().objectForKey("username"), self.bidTextField.text], forKeys: ["user", "name", "bid"])) 

有人能解釋爲什麼嗎?

編輯:這裏是代碼的完整塊

if(self.bidTextField.text!.rangeOfString("^[0-9]*$", options: .RegularExpressionSearch) != nil) { 
        self.sessionBids = array[0].objectForKey("bids") as? NSMutableArray 
        var lastSessionBid : NSDictionary 
        SVProgressHUD.showProgress(50) 
        var previousHighBid : Int! = 0 
        if(self.sessionBids == nil) { 
         self.sessionBids = NSMutableArray() 

        } else { 
         lastSessionBid = self.sessionBids.objectAtIndex(self.sessionBids.count - 1) as! NSDictionary 
         previousHighBid = Int(lastSessionBid.objectForKey("bid") as! String) 
        } 

        if(previousHighBid >= Int(self.bidTextField.text!)) { 
         print("bid is lower than current bid") 
         SVProgressHUD.showErrorWithStatus("Bid is lower than current bid!") 
         return 

        } else { 

         self.sessionBids!.addObject(NSDictionary(objects: [PFUser.currentUser().objectId, PFUser.currentUser().objectForKey("username"), self.bidTextField.text], forKeys: ["user", "name", "bid"])) 
         SVProgressHUD.showProgress(75) 
         self.session.setObject(self.sessionBids, forKey: "bids") 
         self.session.save() 
         self.keyboardShowing = false 
         self.reloadSessionBids() 
         SVProgressHUD.showProgress(100) 
         SVProgressHUD.showSuccessWithStatus("Successfully Added Bid") 
        } 

       } else { 
        SVProgressHUD.showErrorWithStatus("Bid must be a number!") 
       } 
+0

請顯示一些關於'PFUser'。 –

回答

0

兩個物體和字典的鍵不能爲nil
確保所有對象都是非可選項。

+0

如果你能夠給出一些更詳細的建議,我已經發布了我的完整代碼塊:) –

+0

至少在初始化行中展開'self.bidTextField.text!',並且如果它們可能是其他對象'nil' – vadian

0

嘗試調用的NSDictionary的 public init(objects: UnsafePointer<AnyObject?>, forKeys keys: UnsafePointer<NSCopying?>, count cnt: Int)代替:

self.sessionBids!.addObject(NSDictionary(objects: [PFUser.currentUser().objectId, PFUser.currentUser().objectForKey("username"), self.bidTextField.text], forKeys: ["user", "name", "bid"], count: 3)) 

或者,嘗試使用本地字典,而不是一個NSDictionary。

說:

var bidDict = [String : AnyObject]() 
bid["user"] = PFUser.currentUser().objectId ?? "unknown" 
bid["name"] = PFUser.currentUser().objectForKey("username") ?? "unknown" 
bid["bid"] = self.bidTextField.text ?? "unknown" 

然後插入到你的數組:

self.sessionBids!.addObject(bid) 
1

你試圖調用init(objects: [AnyObject], forKeys keys: [NSCopying])初始化的NSDictionary的。 對象:[AnyObject]不能包含可選項(根據其聲明),並且似乎PFUser.currentUser().objectIdPFUser.currentUser().objectForKey("username"),self.bidTextField.text都是可選項,這就是爲什麼你會收到錯誤。

要解決這個問題,正如vadian建議的那樣,您需要展開該數組中的所有可選項。