Skip to content

Instantly share code, notes, and snippets.

@JustinGuedes
Created October 26, 2016 12:52
Show Gist options
  • Save JustinGuedes/a7d296280556bd82d7a75d171e1e1dad to your computer and use it in GitHub Desktop.
Save JustinGuedes/a7d296280556bd82d7a75d171e1e1dad to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Foundation
// Example struct
struct Customer: CustomStringConvertible {
let name: String
let age: Int
var description: String {
return "Beneficiary: \(name) is \(age) years old."
}
}
// Protocol for the customer portal
protocol CustomerPortal {
func getCustomers() throws -> [Customer]
}
// Protocol that contains the customer portal
protocol UsesCustomerPortal {
var customerPortal: CustomerPortal! { get }
}
// Private implementation of the customer portal
struct CustomerPortalImplementation: CustomerPortal {
// contains implemented methods
func getCustomers() throws -> [Customer] {
let customer1 = Customer(name: "Justin", age: 22)
let customer2 = Customer(name: "Leo", age: 100000)
return [customer1, customer2]
}
}
// Default extension for the UsesCustomerPortal (This would be contained in the same file as the CustomerPortalImplementation)
extension UsesCustomerPortal {
// Default implementation for customer portal property
var customerPortal: CustomerPortal! {
return CustomerPortalImplementation()
}
}
// Somewhere in the distant file system we create a view model that uses the UsesCustomerPortal protocol and
// automatically gets the default extension for the customer portal
struct ViewModel: UsesCustomerPortal {
// Some method that uses the repository
func doSomething() {
let customers = try? self.customerPortal.getCustomers()
if let customers = customers {
customers.forEach { print($0.description) }
}
}
}
// Using the view model
let viewModel = ViewModel()
// Do something
viewModel.doSomething()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment