Hi!
I am a long-time Java developer and new to Swift, currently writing my first iOS app.
I am writing an app similar to VVVV or Quartz composer, where you have a set of nodes processing some data and passing the output to a series of listening nodes.
I know the concept of abstract functions is not present in Swift, so I tried to use protocols.
So there's a super-class Node, which holds a Set of other Nodes implementing a protocol.
import Foundation
class Node : Equatable, Hashable {
var id: Int
var name : String?
var listeners : Set<MessageListener>!
init() {
self.name = „Bla“
self.id = 0
self.listeners = Set<MessageListener>()
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
}
static func == (lhs: Node, rhs: Node) -> Bool {
return (lhs.id == rhs.id) && (lhs.name == rhs.name)
}
func addListenerNode(node : Node) {
listeners.insert(node)
}
func removeListenerNode(node : Node) {
listeners.remove(node)
}
internal func output(message: CircuitMessage) {
for node in listeners {
node.receive(message: message)
}
}
}
The protocol consists of just one function receive(message: NodeMessage).
protocol MessageListener : Hashable
{
func receive(message: NodeMessage)
}
I have various subclasses of Node, e.g. SpecialNode1, SpecialNode2, etc. which all do some fancy things upon receiving and use the super class's method to distribute in to the connected nodes
import Foundation
class SpecialNode1 : Node, MessageListener {
init()
{
super.init()
}
func receive(message: NodeMessage) {
//do some fancy stuff to the NodeMessage
//and send it out to the listeners
output(message: midiMessage)
}
}
This approach does not work, because apparently the protocol needs to be Hashable in order to be collected in a Set.
I tried an alternative approach and left out the Protocol, having a Set of <Node> in the Node class and putting the receive() function there, with the subclasses overriding that function. That however leads to the problem that the receive function is always called in the superclass, and not in the respective subclass.
Any ideas how to achieve this?