sulabh
sulabh

Reputation: 249

getting Thrown expression type does not confirm to Error type

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?

Upvotes: 0

Views: 1537

Answers (1)

Dustin Spengler
Dustin Spengler

Reputation: 7711

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()

Upvotes: 1

Related Questions