我正在尝试使用swift中的try catch作为
实现一些函数来从某个函数中获取Integer//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()func处显示错误为"抛出表达式类型'字符串'不确认错误类型'"。
如何解决此问题?
答案 0 :(得分:1)
我让你的代码在操场上工作:
//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()