在 Swift 中使用 localizedDescription 时出错

问题描述 投票:0回答:1

在下面的代码中,我收到错误:

enum errors: Error {
    case too_short, too_obvs
}

func checkPassword(_ passwordEntered: String) throws -> String {
    if passwordEntered.count < 5 {
        throw errors.too_short
    }
    if passwordEntered == "12345" {
        throw errors.too_obvs
    }
    if passwordEntered.count >= 10 {
        return "Password set."
    }
}

let myPassword = "12345"

do {
    let result = try checkPassword(myPassword)
    print("\(result) is your password rating.")
} catch errors.too_short { // customised catch
    print("Password is too short.")
} catch errors.too_obvs {
    print("A 5 yr old would guess that password!")
} catch { // default catch
    print("Error. Enter a stronger password.")
    print("Error: \(error.localizedDescription)") // -> to use default Swift error explanations
}

错误-

错误:“Error”类型的值没有成员“localizedDescription”

print("Error: \(error.localizedDescription)") // -> to use default Swift error explanations

我不明白为什么它会指出

'Error'
,而它甚至没有在打印中使用。

我不明白我在这里缺少什么。任何帮助将不胜感激。谢谢。

swift error-handling syntax-error
1个回答
2
投票

正如其他人所指出的,游乐场有其特殊之处。在实际的应用程序中尝试该代码,您不会得到该特定错误,而是会指出

checkPassword
不会为每个执行路径返回一个值。

但要回答如何为自定义错误类型创建本地化描述这一更广泛的问题,需要添加

LocalizedError
一致性:

enum PasswordError: LocalizedError {
    case tooShort
    case tooObvious

    var errorDescription: String? {
        switch self {
        case .tooShort:   String(localized: "Password is too short", comment: "PasswordError")
        case .tooObvious: String(localized: "Password is too obvious", comment: "PasswordError")
        }
    }
}

(请参阅 iOS 13.x 及更早版本,此答案的先前版本中的再现。)

然后你有一个例程,它为所有执行路径返回一个字符串(但如果你不想,你不必为每个错误都有一个单独的

catch
)。

func passwordRating(_ passwordEntered: String) throws -> String {
    if passwordEntered.count < 5 { throw PasswordError.tooShort }
    if passwordEntered == "12345" { throw PasswordError.tooObvious }

    if passwordEntered.count >= 10 { return "Excellent" }

    return "Acceptable"
}

func validatePassword() {
    do {
        let rating = try passwordRating(myPassword)
        print("\(rating) is your password rating.")
    } catch {
        print("Error. Enter a stronger password.")
        print("Error: \(error.localizedDescription)")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.