Create a class instance (without a Class) from a function in Swift

Keran Marinov
The Startup
Published in
2 min readJun 17, 2020

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 3balance.get()  // get 3balance.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, it gets 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 = balancesecondBalance.add(4)balance.get() // 7balance.add(5)secondBalance.get() // 12balance.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 balance variable which was captured in the closure.

--

--