summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorSpurlow <Spurlow@users.noreply.github.com>2015-11-27 11:43:09 +0700
committerSpurlow <Spurlow@users.noreply.github.com>2015-11-27 11:43:09 +0700
commit997eb086a1a564b558be2bcbfd50d763080a6c90 (patch)
treea9d0542468ca4dfd135af16061689e506227790a
parent4a465720e0b0182b908c16e2fb4f30c453e326ac (diff)
parent50fca171c53ca5c1de63c9a09ca457df0767f713 (diff)
Merge pull request #2037 from cbess/master
- [swift/en] Add error handling examples
-rw-r--r--swift.html.markdown40
1 files changed, 39 insertions, 1 deletions
diff --git a/swift.html.markdown b/swift.html.markdown
index df9c5092..33ff8451 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -346,6 +346,44 @@ let name = namesTable[1]
print("Name is \(name)") // Name is Them
//
+// MARK: Error Handling
+//
+
+// The `ErrorType` protocol is used when throwing errors to catch
+enum MyError: ErrorType {
+ case BadValue(msg: String)
+ case ReallyBadValue(msg: String)
+}
+
+// functions marked with `throws` must be called using `try`
+func fakeFetch(value: Int) throws -> String {
+ guard 7 == value else {
+ throw MyError.ReallyBadValue(msg: "Some really bad value")
+ }
+
+ return "test"
+}
+
+func testTryStuff() {
+ // assumes there will be no error thrown, otherwise a runtime exception is raised
+ let _ = try! fakeFetch(7)
+
+ // if an error is thrown, then it proceeds, but if the value is nil
+ // it also wraps every return value in an optional, even if its already optional
+ let _ = try? fakeFetch(7)
+
+ do {
+ // normal try operation that provides error handling via `catch` block
+ try fakeFetch(1)
+ } catch MyError.BadValue(let msg) {
+ print("Error message: \(msg)")
+ } catch {
+ // must be exhaustive
+ }
+}
+testTryStuff()
+
+//
// MARK: Classes
//
@@ -559,7 +597,7 @@ class MyShape: Rect {
// `extension`s: Add extra functionality to an already existing type
-// Square now "conforms" to the `Printable` protocol
+// Square now "conforms" to the `CustomStringConvertible` protocol
extension Square: CustomStringConvertible {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"