Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Last active February 20, 2019 16:56
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/f105f5e9bd822381a7397dda3f632782 to your computer and use it in GitHub Desktop.
Save jamesrochabrun/f105f5e9bd822381a7397dda3f632782 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
//initialization
//value types get defautlt initializers , structs and enums
//1- failable and throwing initializers
//What happens if we can't initialize an object? This is a common occurrence if initialization depends on external data. Swift gives us two ways to deal with this - failable and throwing initializers.
//FAILABLE INITIALIZER
//if there is no data return nil
class Person {
let name: String
let age: Int
init?(dict:[String : AnyObject]) {
guard let name = dict["name"] as? String, let age = dict["age"] as? Int else {
return nil
}
self.name = name
self.age = age
}
}
//THROWING INITIALIZER
//throwing initializers returns an error on initialization instead of returning nil
//a simple enum for an error case
enum HumanError: Error {
case invalidData
}
class Human {
let name: String
let age: Int
init(dict:[String : AnyObject]) throws {
guard let name = dict["name"] as? String, let age = dict["age"] as? Int else {
throw HumanError.invalidData
}
self.name = name
self.age = age
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment