Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Last active July 17, 2018 07:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesrochabrun/d146ee5e9834c91ef1f7f2ddbe476abd to your computer and use it in GitHub Desktop.
Save jamesrochabrun/d146ee5e9834c91ef1f7f2ddbe476abd to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//compiler errors
//domain error
let number: Int? = Int.init("1")
print(number as Any)
//runtime errors
//recoverable errors
//unrecoverable errors
struct Friend {
let name: String
let age: String
let address: String?
}
//associated value
enum FriendError: Error {
case invalidData(description : String)
case someError
}
func friend(from dict: [String: String]) throws -> Friend {
guard let name = dict["name"] else {
throw FriendError.invalidData(description: "invalinda name")
}
guard let age = dict["age"] else {
throw FriendError.invalidData(description: "invalinda age")
}
let address = dict["address"]
return Friend(name: name, age: age, address: address)
}
func send(message: String, to friend: Friend) {
}
let dict = ["name" : "james",
"ag" : "23",
"address" : "15 el pulgare"]
do {
let myFriend = try friend(from: dict)
send(message: "test", to: myFriend)
} catch FriendError.invalidData(let description) {
//inform the user for invalid data
print(description)
} catch FriendError.someError {
print(FriendError.someError)
}
//creating a model for JSON REQUEST
enum ParserError: Error {
case emptyDictionary
case invalidKey
}
struct Parser {
var data: [String : String?]?
func parse() throws {
guard (data?["someKeyValue"]) != nil else {
throw ParserError.invalidKey
}
guard (data?.keys) != nil else {
throw ParserError.emptyDictionary
}
}
}
let data: [String : String?]? = ["someKeyValue": nil]
let parser = Parser(data: data)
do {
print("test")
try parser.parse()
} catch ParserError.invalidKey {
print(ParserError.invalidKey)
} catch ParserError.emptyDictionary {
print(ParserError.emptyDictionary)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment