mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 17:41:41 +00:00
- added error handling example
- add do-try-catch examples - add throw example
This commit is contained in:
parent
8ca7f472ec
commit
50fca171c5
@ -345,6 +345,44 @@ let namesTable = NamesTable(names: ["Me", "Them"])
|
|||||||
let name = namesTable[1]
|
let name = namesTable[1]
|
||||||
print("Name is \(name)") // Name is Them
|
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
|
// MARK: Classes
|
||||||
//
|
//
|
||||||
@ -559,7 +597,7 @@ class MyShape: Rect {
|
|||||||
|
|
||||||
// `extension`s: Add extra functionality to an already existing type
|
// `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 {
|
extension Square: CustomStringConvertible {
|
||||||
var description: String {
|
var description: String {
|
||||||
return "Area: \(self.getArea()) - ID: \(self.identifier)"
|
return "Area: \(self.getArea()) - ID: \(self.identifier)"
|
||||||
|
Loading…
Reference in New Issue
Block a user