展开可选的value()时意外找到nil

时间:2018-11-05 10:25:42

标签: ios swift

线程1:致命错误:展开错误时意外发现nil。 就在此功能内。

func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
    var dateForDot = dateFormatter.string(from: date)
        self.getScheduleDot(date: dateForDot)
    let dotArr = self.userDefaults.array(forKey: "arrForDotDisplay") as! [String]
        for dateString in dotArr {
            if dateForDot == dateString {
                return 1
            }
        }
    return 0
}

“ getScheduleDot”方法的详细信息如下

func getScheduleDot(date: String) {
    self.db
        .collection("users")
        .document(fireAuthUID)
        .addSnapshotListener { (snapshot, error) in
        guard let document = snapshot else {
            print("erorr2 \(String(describing: error))")
            return
        }
        guard let data = document.data() else { return }
        self.teamIDFromFirebase = data["teamID"] as? String ?? ""

        self.db
            .collection("teams")
            .document(self.teamIDFromFirebase)
            .collection("schedule")
            .whereField("date_start", isEqualTo: date)
            .getDocuments() { (querySnapshot, err) in
            if err != nil {
                print("scheduleを取得できませんでした")
                return
            } else {
                var i = 0
                for document in querySnapshot!.documents {
                    let dataFromFirebase: [String : Any] = document.data()
                    let startDateFromFirebase = dataFromFirebase["date_start"] ?? ""
                    let endDateFromFirebase = dataFromFirebase["date_end"] ?? ""
                    self.dotDisplayArr.append(startDateFromFirebase as! String)
                    self.dotDisplayArr.append(endDateFromFirebase as! String)
                    i += 1
                }

                self.dotDisplayArr as NSArray
                self.userDefaults.removeObject(forKey: "arrForDotDisplay")
                self.userDefaults.set(self.dotDisplayArr, forKey: "arrForDotDisplay")
                self.userDefaults.synchronize()
            }
        }
    }
}

尽管在那之前它一直可以正常工作,但是在更新xcode之后,您会收到此类错误。我想告诉你原因。

1 个答案:

答案 0 :(得分:0)

let dotArr = self.userDefaults.array(forKey: "arrForDotDisplay") as! [String]

检查一下,我认为userDefaults中没有任何内容。将此逻辑包装起来或使用as? [String]并手动检查nil