简体   繁体   中英

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

Swift noobie here trying to follow the tutorial seen here to build a custom sticker application. 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?

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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