如何避免强行打开日期。第二个组件?

时间:2017-05-30 19:30:23

标签: swift macos nsdate

我使用此代码为macOS的文档基础应用程序创建文档,该文档以Date()引用日期后经过的秒数为名。

func saveDocumentInApplicationSupport() {
    do
    {
        // create a directory in Application Support
        let fileManager = FileManager.default
        let appSupportURL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
        appSupportURL.appendingPathComponent("com.myCompany.myApp")
        let directoryURL = appSupportURL.appendingPathComponent("com.myCompany.myApp").appendingPathComponent("Documents")
        try fileManager.createDirectory (at: directoryURL, withIntermediateDirectories: true, attributes: nil)

        // set a name for the file
        let date = Date(timeIntervalSinceReferenceDate: 0) // "2001-01-01 00:00:00 +0000"
        let seconds = Calendar.current.dateComponents([.second], from: date, to: Date()).second // eg. 517848179

        let fileName = "\(seconds!).idoc" // avoid force unwrapping here
        // eg. 517848179.idoc

        //  Create document
        let documentURL = directoryURL.appendingPathComponent (fileName)
        try document.write (to: documentURL, ofType: "com.myCompany.idoc")
    }
    catch
    {
        print("An error occured")
    }
}

避免强制解包秒变量的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

let theDate = Date()

let date = Date(timeIntervalSinceReferenceDate: 0) // "2001-01-01 00:00:00 +0000"
let seconds = Calendar.current.dateComponents([.second], from: date, to: theDate).second!

与直接调用相同:

let seconds = Int(theDate.timeIntervalSinceReferenceDate)

答案 1 :(得分:2)

我认为你正在追逐一只红鲱鱼。您担心这一个强制解包,但您的整个代码块都被包含多个do的{​​{1}} / catch所包围,完全忽略了错误,并且几乎没有做到这一点损害控制。

我唯一的建议是将力展开到try的定义:

seconds

强制展开并非普遍"糟糕" 。您使用强制解包运算符是完全合理的,因为您只是func saveDocumentInApplicationSupport() { do { // create a directory in Application Support let fileManager = FileManager.default let appSupportURL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! appSupportURL.appendingPathComponent("com.myCompany.myApp") let directoryURL = appSupportURL.appendingPathComponent("com.myCompany.myApp").appendingPathComponent("Documents") try fileManager.createDirectory (at: directoryURL, withIntermediateDirectories: true, attributes: nil) // set a name for the file let date = Date(timeIntervalSinceReferenceDate: 0) // "2001-01-01 00:00:00 +0000" let seconds = Calendar.current.dateComponents([.second], from: date, to: Date()).second! let fileName = "\(seconds).idoc" // eg. 517848179.idoc // Create document let documentURL = directoryURL.appendingPathComponent (fileName) try document.write (to: documentURL, ofType: "com.myCompany.idoc") } catch { print("An error occured") } } 定义为具有dateComponents组件。在这种情况下,即使您确实使用条件绑定来安全地"打开你的可选项,你会在.second案例中做些什么?