我正在使用此代碼爲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")
}
}
什麼是避免強制解包秒變量的正確方法?
嘗試使用,如果讓語句設置之前,檢查秒。 –
在這種情況下,如果您完全確定'.second'在那裏(因爲**你把它放在那裏!),你完全有理由強制解包。我只是將解開的力量移動到表達式的末尾。 – Alexander
''com.myCompany.myApp「'字符串應該真的以編程方式獲得...... – Alexander