Post

Replies

Boosts

Views

Activity

Why Isn't Swift Recognizing a Child Class is a Member of a Parent Class?
I have a class Node which has a bunch of child classes, BinaryNode is one of them. In a function I pass a node object as an argument, with intent of checking which child of the node class it is and performing operations based on which one it is. It is throwing errors that Value of type 'Node' has no member '_____' despite those values being a part of the subclass already selected by an if statement. Its best to just see the code directly. I'm guessing the error has something to do with the order of passing a parent class object in and expecting swift to understand that it might be a subclass too, any feedback is appreciated! Class Declaration: public class Node { var spec: String var val: String init(spec: String, val: String) { self.spec = spec self.val = val } } // required to differentiate between Nodes extension Node: Equatable { public static func ==(lhs: Node, rhs: Node) -> Bool { return lhs.spec == rhs.spec && lhs.val == rhs.val } } class UnaryNode: Node { var child: Node init(spec: String, val: String, child: Node) { self.child = child super.init(spec: spec, val: val) } } class BinaryNode: Node { var leftChild: Node var rightChild: Node init(spec: String, val: String, lChild: Node, rChild: Node) { self.leftChild = lChild self.rightChild = rChild super.init(spec: spec, val: val) } } And the part with the error: public func printFunction(root: Node?) { if let node = root { if node is BinaryNode { let left = node.leftChild //Value of type 'Node' has no member 'leftChild' let right = node.rightChild //Value of type 'Node' has no member 'rightChild' //... } else if node is UnaryNode { let child = node.child //Value of type 'Node' has no member 'child' //... } }
2
0
1.1k
Sep ’22