Website Links

Monday, 14 December 2015

Swift - try/catch

In Swift, when a func is marked with throws, it can throw an exception and your code should handle this. This can be done using do/try/catch statements as follows:

  // do contains all statements that should 
  //be executed only if the try succeeds
  do {
    // try comes before the func which is marked with throws
    let modes : [Mode] = try context.executeFetchRequest(request)
      as! [Mode]

    // tried func has succeeded, continue with workflow
    appState.modes = modes.sort({$0.name.compare($1.name) 
      == NSComparisonResult.OrderedAscending}) as [Mode]
  } catch {
    // handle error
    // can handle different types of exceptions separately by their name
  }

No comments:

Post a Comment