gpt4 book ai didi

ios - 获取抛出的表达式类型不符合错误类型

转载 作者:行者123 更新时间:2023-11-28 16:14:30 24 4
gpt4 key购买 nike

我正在尝试实现一些函数,以便在 swift 中使用 try catch 从某个函数获取 Integer as

//Enum 
enum LengthError: ErrorType {
case NoInt
case Default
}


// get Max length From Key else throws error


func getMaximumLength() throws -> Int? {

guard let length = Int(getStringForKey("KEY")) else {
throw LengthError.NoInt
}

return length
}

// This function
func getMaxLength() -> Int {

var maxLength: Int?
do {
maxLength = try getMaximumLength()

} catch LengthError.NoInt {

maxLength = 20

} catch LengthError.Default {
maxLength = 20

} catch {
maxLength = 20
}

return maxLength
}

但是编译器在 getMaximumLength() 函数中显示错误为“Thrown expression type 'String' does not confirm to 'ErrorType'”。

如何解决这个问题?

最佳答案

我让你的代码在 Playground 上工作:

 //Enum
enum LengthError: ErrorType {
case NoInt
case Default
}

func getMaximumLength() throws -> Int? {
guard let length = Int(getStringForKey("KEY")) else {
throw LengthError.NoInt
}

return length
}

// This function
func getMaxLength() -> Int {
var maxLength: Int?
do {
maxLength = try getMaximumLength()
} catch LengthError.NoInt {
maxLength = 20
} catch LengthError.Default {
maxLength = 20
} catch {
maxLength = 20
}

return maxLength!
}

func getStringForKey(key : String) -> String {
if key == "KEY" {
return "654"
} else {
return "none"
}
}

getMaxLength()

关于ios - 获取抛出的表达式类型不符合错误类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39253391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com