0
votes

i am trying to implement some function to get Integer from somefunction using try catch in swift 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
        }

but compiler showing error at getMaximumLength() func as "Thrown expression type 'String ' does not confirm to 'ErrorType'".

how to resolve this issue?

1
@Hamish where do i am missing closing bracket exactly ? and ya currently not worried about optional return , that can be solved easily later., anyways thanks for that - sulabh
ohh that is not a issue in my actual code,, it might got missed during pasting here in stack . - sulabh
Could you please post a minimal reproducible example? The only errors your current code is giving (when compiled in Swift 2.3) is that you're trying to return an optional in a function that expects a non-optional return (return maxLength in getMaxLength()) and the function getStringForKey(_:) isn't defined. - Hamish

1 Answers

1
votes

I got your code to work in the 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()