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

标签 ios swift try-catch

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

相关文章:

ios - SpriteKit bodyWithTexture 未对齐

ios - 如果不在 Swift 的内部范围内使用,是否不保留闭包变量?

ios - 收听键盘按下通知

swift - 如何在 Swift 的 CoreData 实体中的特定索引处添加两个项目

java - 尝试没有捕获错误

java - 尝试在 android 中捕获错误

Java catch 被忽略

ios - 使用 tableviewcontroller 时对导航栏的模糊效果

objective-c - 使用 Accelerate Framework 的 iOS 的 FFT 音调检测?

javascript - iOS 上的 UIWebView 是否有向 DOM 添加接口(interface)的方法?