Tom*_*Tom 5 nsdictionary ios swift
我有这个代码(从另一种语言移植,因此有一些不同的命名约定,但现在请忍受这个)
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);
}
Run Code Online (Sandbox Code Playgroud)
但是,无论我使用哪个setValue变体,对setValue的调用都会抛出一个错误(据我所知无意义)并退出app(Xcode编辑器被带到AppDelegate类:UIResponder,UIApplicationDelegate)
我猜我使用NSDictionary错了?我试图在文本文件中读取每行是key = value字符串
您应该声明一个实际的NSMutableDictionary而不是转换为NSDictionary.
你可以使用比使用更简单的下标setValue(实际应该是setObject):
var FDefaultsList = NSMutableDictionary()
let TmpKey: String = "a"
let TmpValue: String = "b"
if TmpKey != "" && TmpValue != "" {
FDefaultsList[TmpValue] = TmpKey
}
Run Code Online (Sandbox Code Playgroud)
一个更"Swifty"的版本可能是:
var defaultsList = [String:String]()
let tmpKey = "a"
let tmpValue = "b"
if !tmpKey.isEmpty && !tmpValue.isEmpty {
defaultsList[tmpValue] = tmpKey
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6743 次 |
| 最近记录: |