无法弄清楚如何防止 Date 类型崩溃并在 Swift 中换行 3

Unable to figure out how to prevent crash with Date type and wrapping in Swift 3

我正在使用 MPMediaQuery,特别是 Podcasts。在这种特殊情况下,我在使用 Optionals 和 wrapping/unwrapping 时遇到了非常困难的事情。

    titleFilter = MPMediaPropertyPredicate(value: selectedPodcastTitle, forProperty: MPMediaItemPropertyPodcastTitle, comparisonType: .equalTo)
    qryPodcasts.addFilterPredicate(titleFilter)

    for junk in qryPodcasts.items!{

        //works fine
        if let sTitle  = junk.title {
            print("episode title: \(sTitle)")
        }else{
            print("episode title is nil")
        }

        //works fine
        if let dRelease = junk.releaseDate {
            print("episode release date: \(dRelease)")
        }else{
            print("episode release date is nil")
        }
        if #available(iOS 10.0, *) {
            // can't figure out how to make this work
            // crashes on some podcasts and I suspect it's when 'addedDate' is nil
            if let dAdded: Date = junk.dateAdded {
                print("episode added date: \(junk.dateAdded)")
            }else{
                print("episode added date is nil")
            }
        } else {
            print("episode added date is not available")
        }
    }

经过上次讨论,dateAdded 具有不可为空的类型 Date,当它 = nil 时会发生崩溃。

所以我建议它输入 Date? 并且你应该打开它。

 if let dAdded = junk.dateAdded {
 }

或检查它会 nil 在这种情况下。

 if junk.dateAdded != nil {
 }

似乎 dateAdded 的可空性在当前 iOS SDK 中被错误注释,您可能需要一些解决方法。

试试这个扩展:

extension MPMediaItem {
    func getAddedDate() -> Date? {
        return self.perform(#selector(getter: MPMediaItem.dateAdded))?.takeUnretainedValue() as! NSDate? as Date?
    }
}

并像这样使用它:

        if let dAdded = junk.getAddedDate() {
            print("episode added date: \(dAdded)")
        }else{
            print("episode added date is nil")
        }

您最好向 Apple 发送有关此问题的错误报告。 (可能会被归类为重复,但数量可能会影响。)