This short blog was inspired when I was watching an** MIT/GNU Scheme**tutorial on Youtube and thought to convert Scheme code example into Swift.
Scheme is a functional programming language and it does not have classes, but it has the mechanisms to create a class instance just by using functions.
In the code below I have attempted to translate Scheme code in the shortest possible way implemented in Swift.
typealias Balance = (add: ((Int) -> Void), get: (() -> Int), print: () -> ())
func newBalance() -> Balance {
var balance = 0
return (
add: { newValue in balance += newValue },
get: { return balance },
print: { print("Your balance is \(balance)") }
)
}
let balance = newBalance()
balance.add(3) // add 3
balance.get() // get 3
balance.print() // prints the balance
The code is quite explanatory. But I will try to summarise, on what is going on, newBalance is a function which returns a tuple which is type aliased to Balance, also the tuple has labels for each value such as add, get, print, just to make it more user friendly.
A tuple is value type but the functions are reference types so inside the tuple we have 3 methods which are reference types.
When we have assigned the newBalance() to the property **balance, **itgets the tuple value assigned which has 3 methods. The balance value with the **Int type **gets captured in the closures even though Int is value type it gets captured by reference in the closures.
var secondBalance = balance
secondBalance.add(4)
balance.get() // 7
balance.add(5)
secondBalance.get() // 12
balance.get() // 12
Now you can also assign the balance as a reference type to the **secondBalance **property, but it would still mutate on the same balancevariable which was captured in the closure.
#ios #swift #scheme #functional-programming #closure