0

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.

Gabriel
  • 27
  • 6
  • 1
    This is completely valid but with several comments: 1. calling things `method` is pretty bad, just call it `converter`. 2. Usually people won't pass `func`, they will pass a closure directly. 3. It can be easily used on structs, even on constant strucs. However, depending on your architecture, it could be more readable to make every unit as a subclass instead of generating them dynamically. – Sulthan May 11 '15 at 09:19
  • Thanks for the feedback! yeah I just called it `method` here to make it clear in the class definition. If I used subclasses, would i have to make instances before I can call their methods? – Gabriel May 11 '15 at 09:29
  • That really depends on how you do it. You can have class methods. – Sulthan May 11 '15 at 09:31

0 Answers0