【问题标题】:getting Thrown expression type does not confirm to Error type获取抛出的表达式类型不确认为错误类型
【发布时间】:2017-01-08 06:25:02
【问题描述】:

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

//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() 函数处显示错误为“抛出的表达式类型 'String' 不确认为 'ErrorType'”。

如何解决这个问题?

【问题讨论】:

  • @Hamish 我到底在哪里缺少右括号?而且你目前不担心可选的 return ,以后可以轻松解决。无论如何,谢谢
  • 哦,这在我的实际代码中不是问题,在将其粘贴到堆栈中时可能会丢失。
  • 你能发一个minimal reproducible example吗?当前代码给出的唯一错误(在 Swift 2.3 中编译时)是您试图在一个函数中返回一个可选项,该函数需要一个非可选返回(getMaxLength() 中的 return maxLength)和函数 getStringForKey(_:)未定义。

标签: ios swift try-catch


【解决方案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()

【讨论】:

  • 好吧,谢谢,我清理并再次构建,问题消失了。无论如何,似乎像 xcode 问题:)
  • 我以前也遇到过这种情况。这可能是一个真正的头痛!希望我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多