Last active
February 20, 2019 16:56
-
-
Save jamesrochabrun/f105f5e9bd822381a7397dda3f632782 to your computer and use it in GitHub Desktop.
This file contains 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
//: 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