[英]Cannot convert value of type '()?' to specified type Bool
I try to write code which changes property of file, but I get a compiler error. 我尝试编写更改文件属性的代码,但出现编译器错误。
Here is the code: 这是代码:
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
}
and the error is: 错误是:
Cannot convert value of type '()?' 无法转换类型'()的值? to specified type 'Bool' 到指定类型“布尔”
How can I fix it? 我该如何解决?
Call to url?.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey)
doesn't return a Bool
. 调用url?.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey)
不会返回Bool
。 You are expecting a Bool
as response. 您期待Bool
作为回应。 Thats the reason for error. 多数民众赞成在错误的原因。
Apple documentation for setResourceValue
method says 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. 在Swift中,此方法返回Void
并用throws
关键字标记,以指示在失败的情况下抛出错误。
do {
try url?.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)
//...
}
catch let error as NSError {
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.