Error “Call can throw, but is not marked with 'try' and the error is not handled”

前端 未结 1 481
心在旅途
心在旅途 2021-01-03 13:04

Getting an error with this piece of code \"Call can throw, but is not marked with \'try\' and the error is not handled\"

I am using the Xcode 7.1 the latest beta a

相关标签:
1条回答
  • 2021-01-03 13:26

    Swift 2.0 introduces error handling. The error indicates that logInWithUsername:password: can potentially throw an error, and you must do something with that error. You have one of a few options:

    Mark your checkUserCredentials() functional as throws and propagate the error to the caller:

    func checkUserCredentials() throws -> Bool {
        try PFUser.logInWithUsername(userName!, password: password!)
    
        if (PFUser.currentUser() != nil) {
            return true
        }
        return false
    }
    

    Use do/catch syntax to catch the potential error:

    func checkUserCredentials() -> Bool {
        do {
            try PFUser.logInWithUsername(userName!, password: password!)
        }
        catch _ {
            // Error handling
        }
    
        if (PFUser.currentUser() != nil) {
            return true
        }
        return false
    }
    

    Use the try! keyword to have the program trap if an error is thrown, this is only appropriate if you know for a fact the function will never throw given the current circumstances - similar to using ! to force unwrap an optional (seems unlikely given the method name):

    func checkUserCredentials() -> Bool {
        try! PFUser.logInWithUsername(userName!, password: password!)
    
        if (PFUser.currentUser() != nil) {
            return true
        }
        return false
    }
    
    0 讨论(0)
提交回复
热议问题