Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS NSDictionary setValue crash - but why?

I have this code (porting from another language, hence a bit different naming conventions, but please bear with this for now)

var FDefaultsList: NSDictionary = [String:String]();
let TmpKey: String = TmpKeyValue[0];
let TmpValue: String = TmpKeyValue[1];    
if (TmpKey != "") && (TmpValue != "") {
  //let TmpAnyObjectValue: AnyObject? = TmpValue;
  //FDefaultsList.setValue(TmpAnyObjectValue, forKey: TmpKey);
  FDefaultsList.setValue(TmpValue, forKey: TmpKey);
}

However, no matter the which setValue variation I use, the call to setValue throws an error (not meaningful as far as I can tell) and exits app (Xcode editor is taken to class AppDelegate: UIResponder, UIApplicationDelegate)

I guess I am using NSDictionary wrong? I am trying to read in a text file where each line is key=value strings

like image 490
Tom Avatar asked Jan 28 '16 15:01

Tom


1 Answers

You should declare an actual NSMutableDictionary instead of casting to NSDictionary.

And you can use subscript which a bit simpler to use than setValue (which should actually be setObject):

var FDefaultsList = NSMutableDictionary()
let TmpKey: String = "a"
let TmpValue: String = "b"
if TmpKey != "" && TmpValue != "" {
    FDefaultsList[TmpValue] = TmpKey
}

A more "Swifty" version could be:

var defaultsList = [String:String]()
let tmpKey = "a"
let tmpValue = "b"
if !tmpKey.isEmpty && !tmpValue.isEmpty {
    defaultsList[tmpValue] = tmpKey
}
like image 70
Eric Aya Avatar answered Nov 07 '22 13:11

Eric Aya