ios - 错误 "Call can throw, but is not marked with ' try' 错误未被处理”

标签 ios xcode swift parse-platform error-handling

这段代码出错 “调用可以抛出,但没有标上‘try’,错误未被处理”

我正在使用 Xcode 7.1 最新的 beta 和 swift 2.0

func checkUserCredentials() -> Bool {
    PFUser.logInWithUsername(userName!, password: password!)

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false

enter image description here

最佳答案

Swift 2.0 引入了 error handling .该错误表明 logInWithUsername:password: 可能会引发错误,您必须对该错误采取一些措施。您有以下几种选择之一:

将您的 checkUserCredentials() 功能标记为 throws 并将错误传播给调用者:

func checkUserCredentials() throws -> Bool {
    try PFUser.logInWithUsername(userName!, password: password!)

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false
}

使用do/catch语法来捕捉潜在的错误:

func checkUserCredentials() -> Bool {
    do {
        try PFUser.logInWithUsername(userName!, password: password!)
    }
    catch _ {
        // Error handling
    }

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false
}

使用 try! 关键字让程序在抛出错误时陷入陷阱,这仅适用于您知道在当前情况下该函数永远不会抛出的事实 - 类似于使用 ! 强制展开一个可选的(给定方法名称似乎不太可能):

func checkUserCredentials() -> Bool {
    try! PFUser.logInWithUsername(userName!, password: password!)

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false
}

关于ios - 错误 "Call can throw, but is not marked with ' try' 错误未被处理”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32997955/

相关文章:

ios - 如何检查 Objective c 中是否没有服务器响应

ios - 如何从 Xamarin IOS 获取唯一的 DeviceID

ios - SKShapeNode.fillColor 不等于原始 UIColor

html - 尝试在 iOS 中解析 html 表格

ios - 当应用程序将终止时如何运行异步/等待任务?

objective-c - iOS 新手。预期的表达错误?

ios - xcode/ios 应用程序分发临时

ios - 搜索后访问索引路径行

ios - 重用 UIView 会导致应用卡住

ios - 在谷歌地图上放置公交车站标记