Skip to content

Instantly share code, notes, and snippets.

@kabutz
Created October 12, 2016 15:49
Show Gist options
  • Save kabutz/d3153f189d5c2aa5ba528a3f9971720f to your computer and use it in GitHub Desktop.
Save kabutz/d3153f189d5c2aa5ba528a3f9971720f to your computer and use it in GitHub Desktop.
Example of how easily we can build a "virtual proxy" in Swift 3.0
/*
All it takes is the "lazy" keyword in front of the var definition and the object is instantiated when it is first used. Brilliant.
*/
class MoralFibre {
init() {
print("***Creating MoralFibre***")
}
func actSociallyResponsibly() -> Int {
print("supporting local soup kitchen")
return 100_000
}
func empowerEmployees() -> Int {
print("giving shares to our beloved employees")
return 300_000
}
func cleanupEnvironment() -> Int {
print("sending money to SANCCOB")
return 1_500_000
}
}
class Company : CustomStringConvertible {
lazy var moralFibre = MoralFibre() // virtual proxy pattern
var cash : Int
let name : String
init(name : String, cash : Int = 0) {
print("***Creating Company***")
self.name = name
self.cash = cash
}
func makeMoney() {
cash += 1_000_000
print("Making tons of cash \(self)")
}
func destroyEnvironment() {
cash += 2_000_000
print("Sacrificing baby seals for profit \(self)")
}
func becomeFocusOfMediaAttention() {
cash -= moralFibre.actSociallyResponsibly()
cash -= moralFibre.empowerEmployees()
cash -= moralFibre.cleanupEnvironment()
print("Poor \(self)")
}
var description: String {
return "Company \(name) has $\(cash)"
}
}
let cretesoft = Company(name:"Cretesoft Limited", cash:10_000_000)
cretesoft.makeMoney()
cretesoft.makeMoney()
cretesoft.makeMoney()
cretesoft.destroyEnvironment()
cretesoft.makeMoney()
cretesoft.becomeFocusOfMediaAttention()
/*
Output is:
***Creating Company***
Making tons of cash Company Cretesoft Limited has $11000000
Making tons of cash Company Cretesoft Limited has $12000000
Making tons of cash Company Cretesoft Limited has $13000000
Sacrificing baby seals for profit Company Cretesoft Limited has $15000000
Making tons of cash Company Cretesoft Limited has $16000000
***Creating MoralFibre***
supporting local soup kitchen
giving shares to our beloved employees
sending money to SANCCOB
Poor Company Cretesoft Limited has $14100000
*/
/*
If we take away the "lazy" keyword, then we will have output:
***Creating MoralFibre***
***Creating Company***
Making tons of cash Company Cretesoft Limited has $11000000
Making tons of cash Company Cretesoft Limited has $12000000
Making tons of cash Company Cretesoft Limited has $13000000
Sacrificing baby seals for profit Company Cretesoft Limited has $15000000
Making tons of cash Company Cretesoft Limited has $16000000
supporting local soup kitchen
giving shares to our beloved employees
sending money to SANCCOB
Poor Company Cretesoft Limited has $14100000
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment