【问题标题】:I can't Unwrap a value from a plist key value我无法从 plist 键值中解包值
【发布时间】:2020-10-05 18:17:30
【问题描述】:

我是 swift 新手,我正在尝试将属性从 nsDictionary 加载到 vTitle

var nsDictionary: NSDictionary?
         if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
            nsDictionary = NSDictionary(contentsOfFile: path)
         }
let vTitle:String = nsDictionary["LbVacationsTitle"]

当我调试时,我在 nsDictionary 中看到了正确的键,但我不能只解开一个键的值 LbVacationsTitle 的类型是字符串

【问题讨论】:

  • 你能发布一些调试信息吗?就像path 不是零? nsDictionary 是零吗?你能打印出来吗?此外,在 Swift 4+ 中,建议使用 Codable 和 PropertyList 解码器。
  • @Larme 路径和 nsDictionary 不是零。 Tx 回复

标签: swift nsdictionary


【解决方案1】:

取决于您的风格偏好...

var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
    nsDictionary = NSDictionary(contentsOfFile: path)
}
if let dict = nsDictionary {
    let vTitle = dict["LbVacationsTitle"] as? String
    if let vt = vTitle {
        // ...
    }
}

...或...

var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
    nsDictionary = NSDictionary(contentsOfFile: path)
}
guard let dict = nsDictionary else {
    print("Couldn't get a valid dictionary")
    return
}
let vTitle = dict["LbVacationsTitle"] as? String
guard let vt = vTitle else {
    print("Couldn't find a string matching LbVacationsTitle")
    return
}
// ...

【讨论】:

  • 我用了第二个带保护的,效果很好。发送
【解决方案2】:

请不要在 Swift 中使用NSDictionary API 来读取属性列表。

PropertyListSerialization(甚至PropertyListDecoder

let url = Bundle.main.url(forResource: "AppData", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let dictionary = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
let vTitle = dictionary["LbVacationsTitle"] as! String

由于文件在应用程序包中是不可变的,因此任何崩溃都表明存在设计错误

【讨论】:

  • 有时崩溃是可取的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多