Alexey K
Alexey K

Reputation: 6723

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?

Upvotes: 2

Views: 2585

Answers (1)

R P
R P

Reputation: 1193

Call to url?.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey) doesn't return a Bool. You are expecting a Bool as response. Thats the reason for error.

Apple documentation for setResourceValue method says

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 {
     //...
}

Upvotes: 2

Related Questions