简体   繁体   English

Swift-使用&#39;as!时为零! 字典 <String, AnyObject> &#39;

[英]Swift - Nil when using 'as! Dictionary<String, AnyObject>'

Swift noobie here trying to follow the tutorial seen here to build a custom sticker application. 这里斯威夫特noobie试图跟随看到的教程在这里建立一个自定义标签的应用。 I am able to compile the application to a simulator but not to my phone. 我可以将应用程序编译为模拟器,但不能编译为手机。

The initial code is as follows: 初始代码如下:

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

The line causing me issue is 引起我问题的线是

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

I am not sure how to revise the code to prevent the unwrapping of the optional value as I am not seeing direct examples that help me recode this portion of the code. 我不确定如何修改代码以防止可选值的解包,因为我没有看到直接的示例可以帮助我重新编码这部分代码。 Could anyone please advise and explain what is going on with my variables and whether it is index.description , data , selectedSections , or something else causing the problem? 谁能提出建议并解释我的变量发生了什么以及它是index.descriptiondataselectedSections还是其他导致问题的原因?

Thank you guys! 感谢大伙们!

You are on the right track. 您走在正确的轨道上。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM