With this simplified Unit
class, I have an unset method called myMethod
which is initialised when a new instance is created.
typealias Converter = (input: Double) -> Double
class Unit {
let name: String
let myMethod: Converter
init(name: String, method: Converter) {
self.name = name
self.myMethod = method
}
}
To create an instance of this class I attach a Converter
type function (celsiusToKelvin()
) in the initialisation as below:
func celsiusToKelvin(input: Double) -> Double { return input + 273.15 }
let celsius = Unit(name: "Celsius", method: celsiusToKelvin)
Now I can use the celsius.myMethod()
the same as any instance method, even though I didn't define it as a func
in the Unit
class.
Questions:
1) Is this a valid approach for adding methods to particular instances of a class?
2) Can it also be done for a struct
?
3) Are there other (better/safer) ways to achieve this?
Thanks.