我尝试编写更改文件属性的代码,但出现编译器错误。
这是代码:
func addSkipBackupAttributeToItemAtURL(URL: NSURL) -> Bool{
let fileManager = NSFileManager.defaultManager()
assert(fileManager.fileExistsAtPath(URL.absoluteString))
var error:NSError?
let success:Bool = try? URL.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey)
if !success {
print("Error excluding \(URL.lastPathComponent) from backup \(error)")
} else {
print("File at path \(URL) was succesfully updated")
}
return success
}
错误是:
Cannot convert value of type '()?' to specified type 'Bool'
如何修复它?
最佳答案
调用 url?.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey)
不会返回 Bool
。您期望得到 Bool
作为响应。这就是错误的原因。
Apple 文档中有关 setResourceValue
方法的说明
In Swift, this method returns
Void
and is marked with thethrows
keyword to indicate that it throws an error in cases of failure.
do {
try url?.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)
//...
}
catch let error as NSError {
//...
}
关于swift - 无法将 '()?' 类型的值转换为指定的 Bool 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34210898/