Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

swift - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...