Swift - 使用'as时为零!字典<string,anyobject =“”>'

时间:2017-08-23 04:45:55

标签: ios arrays swift

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

谢谢你们!

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上。

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