[英]swift mutating method sent to immutable object
我只是無法繞過這個錯誤,我試圖在一個數組中添加一個字符串,就像我總是在objective-c中做的那樣,但是swift給了我一個奇怪的錯誤。
var fileArray:NSMutableArray = []
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
self.fileArray.addObject(self.urlTextField.text)
self.processURL()
}))
錯誤:
因未捕獲的異常'NSInternalInconsistencyException'而終止應用程序,原因:' - [__ NSCFArray insertObject:atIndex:]:發送到immutable對象的mutating方法'
fileArray
是如何不可變的? 我宣布它為MutableArray !!!!!!
編輯:::所以事實證明問題是我填充數組的方式
fileArray = myDict?.valueForKey("fileList") as! NSMutableArray
這解決了這個問題
fileArray = myDict?.valueForKey("fileList")!.mutableCopy() as! NSMutableArray
一個數組不會因為你聲明它而變得可變,或者因為你把它變成可變的as! NSMutableArray
as! NSMutableArray
。 如果數組使用[[NSMutableArray alloc] ....]
創建為可變數組,或者通過創建數組的mutableCopy,則數組只是可變的。
(字典,字符串,NSSet和NSData也是如此)
由於你的數組只包含一個類型,我建議使用Swift類型,它更容易, var
是可變的, let
是不可變的
var fileArray : Array<String> = []
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
self.fileArray.append(self.urlTextField.text)
self.processURL()
}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.