ios - Swift - 使用 'as! Dictionary<String, AnyObject>' 时为零

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

谢谢大家!

最佳答案

你走在正确的轨道上。

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

相关文章:

java - 在Java中测试数组的多个维度的长度

ios - 从推送通知(FCM)获取数据,无需点击通知

xcode - 如何重新打开应用程序窗口,Xcode

ios - 水平边界在 SpriteKit 中不起作用

ios - SAPUI5:如何在 iOS 上更新或清除主屏幕应用程序的缓存

iphone - iPhone/iPad 应用程序启动时发出警报

javascript - 将 ajax 响应数组对象转换为 javascript 数组?

ios - 单元格在 UITableView 中显示为空白

ios - 当没有 self.view 时,如何找到 UIView...?

c - C中指向字符串数组的指针