Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Error Handling in Swift 2.0 Error Handling Handling Errors

Ludwig Jonsson
Ludwig Jonsson
6,426 Points

called method without parameters.

S0 i was doing a test from Handling Errors in the Swift course and i couldn't get my do {} catch {} statements to work. code posted below

enum ParserError: ErrorType {
  case EmptyDictionary
  case InvalidKey
}

struct Parser {
  var data: [String : String?]?

  func parse() throws {
  guard let isDataNil = data else {
      throw ParserError.EmptyDictionary
     }
     let keysNil = isDataNil.keys
     let containsKey = keysNil.contains("someKey") 
     if containsKey == false {
        throw ParserError.InvalidKey
     }
   }
}

let data: [String : String?]? = ["someKey": nil]
let parser = Parser(data: data)

do {
   let baby = try Parser.parse()
}
catch {
    print("Error!")
}

Now i managed to pass the test when i removed the empty paranthesis from try Parser.parse() so it just said try Parser.parse . Is this really the right way? Since i've never before seen a method being called without parenthesis

/Thanks

1 Answer

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

Hey there. No, this does not work :) Seems you have tricked code check into passing this challenge, but this will throw an error in Xcode Playgrounds. The following will work as expected:

let data: [String : String?]? = ["someKey": nil]
let parser = Parser(data: data)

do {
   // You have to call parse on the instance of Parser
   // you created before, that is parser
   let baby = try parser.parse()
}
catch {
    print("Error!")
}

Btw., there are methods that can be called on classes directly, then no parenthesis are needed. Those are called class or static methods, as opposed to instance methods. Example: UIColor.blackColor().

Hope that helps :)