March 2017
Intermediate to advanced
226 pages
5h 13m
English
Swift offers two variations of try that bypass normal error handling: try! halts execution if an error is thrown. try? converts throwing results into optionals, returning a wrapped value on success or nil otherwise. Using try? discards errors.
Forcing crashes (with try!) and discarding errors by coercing results to optionals (with try?) are not good practices. At a minimum, prefer to catch and log errors instead of ignoring them entirely:
| | public func attempt<T>(closure: () throws -> T) -> T? { |
| | do { return try closure() } |
| | catch { print(error); return nil } |
| | } |
Avoid forced trys ...
Read now
Unlock full access