Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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