我正在尝试实现一些函数,以便在 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/