Created
June 17, 2016 10:55
-
-
Save jon-cotton/abc6caad8be137193d4e1e58cc8d2e06 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 Foundation | |
enum PersonError: ErrorProtocol { | |
case doesNotExistInDataSource | |
case emailNotInPersonalData | |
} | |
struct Person { | |
let name: String | |
let age: Int | |
private(set) var emailAddress: String? | |
init(name: String, age: Int) { | |
self.name = name | |
self.age = age | |
} | |
mutating func setEmailAddress(from dataSource: [String : AnyObject]) throws { | |
guard let personData = dataSource[name] as? [String : AnyObject] else { | |
throw PersonError.doesNotExistInDataSource | |
} | |
guard let emailAddress = personData["email"] as? String else { | |
throw PersonError.emailNotInPersonalData | |
} | |
self.emailAddress = emailAddress | |
} | |
} | |
let ted = Person(name: "Ted", age: 24) | |
let sarah = Person(name: "Sarah", age: 42) | |
let brad = Person(name: "Brad", age: 38) | |
let julie = Person(name: "Julie", age: 20) | |
let VIPs = [ted, sarah] | |
let others = [brad, julie] | |
let contactInfo = [ | |
"Ted": ["email": "ted@ted.me"], | |
"Sarah": ["telephone": "05556789555"], | |
"Brad": ["email": "brad@hotmail.com"] | |
] | |
var all = [Person]() | |
// VIPs must have an email address | |
for var importantPerson in VIPs { | |
do { | |
try importantPerson.setEmailAddress(from: contactInfo) | |
all.append(importantPerson) | |
} catch let personError as PersonError { | |
switch personError { | |
case .doesNotExistInDataSource: | |
print("Error: Supplied data does not contain \(importantPerson.name)'s data") | |
case .emailNotInPersonalData: | |
print("Error: \(importantPerson.name)'s data does not contain an email address") | |
} | |
} | |
} | |
// For non-VIPs, the email address is optional | |
for var person in others { | |
try? person.setEmailAddress(from: contactInfo) | |
all.append(person) | |
} | |
print("=======") | |
for person in all { | |
print(person) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment