斯威夫特 - 使用'as! Dictionary<String, AnyObject>'时为零



这里的 Swift 菜鸟试图按照这里看到的教程来构建一个自定义贴纸应用程序。我可以将应用程序编译到模拟器,但不能编译到我的手机。

初始代码如下:

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还是其他导致问题的原因?

谢谢你们!

你走在正确的轨道上。

// 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
}

相关内容

最新更新