【问题标题】:Swift - Nil when using 'as! Dictionary<String, AnyObject>'Swift - 使用'as!字典<String, AnyObject>'
【发布时间】:2017-08-23 04:45:54
【问题描述】:

Swift noobie 在这里尝试按照看到的教程here 构建自定义贴纸应用程序。我能够将应用程序编译到模拟器,但不能编译到我的手机。

初始代码如下:

class FoodDrawerCollectionViewController: UICollectionViewController {
let numberOfItemsPerRow = 3.0 as CGFloat
let interItemSpacing = 1.0 as CGFloat
let interRowSpacing = 1.0 as CGFloat
let sectionTitleKey = "SectionTitle"
let sectionItemsKey = "Items"
var data = [Dictionary<String,AnyObject>]()
override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView?.contentInset = UIEdgeInsets(top: 80, left: 0, bottom: 40, right: 0)
    if let path = Bundle.main.path(forResource: "FoodDrawerData", ofType: ".plist") {
        let dict = NSDictionary(contentsOfFile: path) as! Dictionary<String,AnyObject>
        let allSections = dict["Sections"]
        if let selectedSections = UserDefaults.standard.array(forKey: "selectedSections") as? [Int] {
            for index in selectedSections {
                    self.data.append((allSections![index.description]) as! Dictionary<String, AnyObject>)
            }
        }
    }
}

导致我出现问题的行是

 self.data.append((allSections![index.description]) as! Dictionary<String, AnyObject>)

我不确定如何修改代码以防止解开可选值,因为我没有看到可以帮助我重新编码这部分代码的直接示例。谁能建议并解释我的变量发生了什么以及是index.descriptiondataselectedSections,还是其他导致问题的原因?

谢谢你们!

【问题讨论】:

  • 尝试使用 [String : AnyObject]
  • 这是一个非常糟糕的教程。它使用 , 而不是 : 和大量的力展开
  • 确实如此。尽可能远离!,并始终检查您的选项是否包含if letguard letas? 等的值。

标签: ios arrays swift


【解决方案1】:

你在正确的轨道上。

    // use as? instead of as!
    // it might return nil
    let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String,AnyObject>
    if let dict = dict {
        // the following might be nil
        if let allSections = dict["Sections"] {
            // Sections was found
        }
        else {
            // Sections not found
        }
    }
    else {
        // dict is nil
    }

【讨论】:

  • 从应用程序包中检索的数据的可选绑定是无稽之谈。 创建了文件,它不能是nil,并且你知道它的内容类型。
  • 没错。如果它 nil,那么你想要崩溃并修复文件,而不是处理错误。
  • 这是您的意见。随心所欲地在您的代码中处理它。我宁愿优雅地处理任何异常情况。
  • 这不是意见,这是事实。处理可选项时不仅仅是黑白。设计(时间)错误(可控)和运行时错误(不可控制)之间存在显着差异。
猜你喜欢
  • 2015-08-12
  • 2019-01-28
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多