我正在使用此代码为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