swift - 无法将 '()?' 类型的值转换为指定的 Bool 类型

标签 swift

我尝试编写更改文件属性的代码,但出现编译器错误。

这是代码:

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 the throws 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/

相关文章:

ios - SwiftUI:通过数据库连接实现评级 View

ios - 是否可以在应用程序运行时在设备上训练 CoreML 模型?

ios - 在 UICollectionView swift 中获取单元格 onClick 的所有 subview

ios - Swift 4.2 使用多个字符作为分隔符提取子字符串

ios - SwiftUI - 在导航堆栈中弹回不会释放 View

ios - Swift 中的变量声明是什么类型

ios - 完成处理程序在 viewDidLoad 中不起作用?

swift - 当保存在后台异步完成时,我应该如何保证嵌套上下文中不同线程的获取结果是最新的?

ios - 从 WKWebView 调用时无法使用 JavaScript 在移动 Safari 中打开链接

ios - scrollView contentOffset y 更改时如何动态更改字体大小?