0

I want to send a store a method address in a class, allowing the class to call that method. I want this class to be Hashable, and I want the hashValue to be calculated from the method such that 2 objects pointing to the same method have the same hashValue.

Here is the class init that attempts to calculate the hashValue, but it fails. I think it hashes a pointer to the local variable.

typealias functionAlias = ((Double) -> ())?

class FunctionPointer: Hashable {
private let functionPointer: functionAlias
private let hash: Int

init( functionPointer: functionAlias ) {
    self.functionPointer = functionPointer
    var f = functionPointer
    var h = 0
    withUnsafePointer(to: &f, {
        ptr in
        h = ptr.hashValue
    })
    self.hash = h
    print("self.hash = \(self.hash)")
}

}

Thanks

  • Somewhat related: [How do you test functions and closures for equality?](http://stackoverflow.com/q/24111984/2976878) Even if you were to get the pointer value of the function, you would likely encounter surprising results when the compiler uses thunks or optimisations such as specialisation. You could have two different pointer values for functions that would otherwise seem to be equivalent. What's the actual problem you're trying to solve here? – Hamish Apr 20 '17 at 11:04
  • I want to allow messages to be sent between classes. The sending class is passed a series of methods that it calls when is receives a message. However, given your answer, I think I will create a hash based on the method’s parent object which I know how to do. Thanks. – Jonathan Stanley-Smith Apr 20 '17 at 11:16

0 Answers0