Last active
August 29, 2015 14:22
-
-
Save delba/a4dbc258ec94f0637c15 to your computer and use it in GitHub Desktop.
Typing the throwable errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func catchAll(name: String?) { | |
do { | |
try throwSomething(name) | |
} catch { | |
print("An error occured") | |
} | |
} | |
func catchAllWithReference(name: String?) { | |
do { | |
try throwSomething(name) | |
} catch let error { | |
print("This error occured: \(error)") | |
} | |
} | |
func catchNameError(name: String?) { | |
do { | |
try throwSomething(name) | |
} catch is NameError { | |
print("A NameError occured") | |
} catch { | |
print("An Error occured") | |
} | |
} | |
func catchNameErrorWithReference(name: String?) { | |
do { | |
try throwSomething(name) | |
} catch let error where error is NameError { | |
print("A NameError occured: \(error)") | |
} catch { | |
print("An Error occured") | |
} | |
} | |
func catchNameErrorMessages(name: String?) { | |
do { | |
try throwSomething(name) | |
} catch let NameError.Nil(message) { | |
print(message) | |
} catch let NameError.Wrong(message) { | |
print(message) | |
} catch { | |
print("An Error occured") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum NameError: ErrorType { | |
case Nil(String) | |
case Wrong(String) | |
init?(name: String?) { | |
switch name { | |
case .None: | |
self = .Nil("can't be nil") | |
case let .Some(name) where name == "damien": | |
self = .Wrong("can't be damien") | |
default: | |
return nil | |
} | |
} | |
} | |
func throwSomething(name: String?) throws { | |
if let error = NameError(name: name) { | |
throw error | |
} | |
} | |
let names: [String?] = [nil, "damien", "sophie"] | |
for name in names { | |
catchAll(name) | |
catchAllWithReference(name) | |
catchNameError(name) | |
catchNameErrorWithReference(name) | |
catchNameErrorMessages(name) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func throwSomething(name: String?) throws(NameError) { | |
if let error = NameError(name: name) { | |
throw error | |
} | |
} | |
do { | |
try throwSomething(nil) | |
} catch let .Nil(message) { | |
print(message) | |
} catch let .Wrong(message) { | |
print(message) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment