我试图转换为swift代码,它将files属性设置为“不备份到iCloud”
原始代码如下所示
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString {
NSURL* URL= [NSURL fileURLWithPath: filePathString];
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
}
return success;
}
我带了这样的代码
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
}
但它会在let success:Bool
无法转换类型'()的值?'指定类型'Bool'
如何解决这个问题?
答案 0 :(得分:3)
setResourceValue未返回Bool
表示成功,但在失败时抛出错误。所以你应该将它包装在try catch
块中。
好了,̶文档看起来已经过时,该文档描述的错误处理斯威夫特在底部,但如果你跳这是defenition,你会看到,该方法不返回任何内容:
public func setResourceValue(value: AnyObject?, forKey key: String) throws