gpt4 book ai didi

ios - Swift - 使用 'as! Dictionary' 时为零

转载 作者:行者123 更新时间:2023-11-28 08:03:38 30 4
gpt4 key购买 nike

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

谢谢大家!

最佳答案

你走在正确的轨道上。

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

关于ios - Swift - 使用 'as! Dictionary<String, AnyObject>' 时为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45830810/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com