I did a project in C# for a class that would use a tree to solve mathematical expressions. I had two classes : ExpressionTree and ExpressionTreeLeaf
I had two constructors for the ExpressionTree
public ExpressionTree(string d)
{
Data = d;
Left = null;
Right = null;
}
public ExpressionTree(string d, ExpressionTree left, ExpressionTree right)
{
Data = d;
Left = left;
Right = right;
}
I also had an ExpressionTreeLeaf constructor
public ExpressionTreeLeaf(int n) : base(n.ToString())
{
_num = n;
}
I understand that the :base(n.ToString())
is used to call the parent constructor. How do I do this in Swift?
CodePudding user response:
This can be achieved by simply calling super.init
:
class ExpressionTree {
let data: String
let left: ExpressionTree?
let right: ExpressionTree?
init(data: String, left: ExpressionTree? = nil, right: ExpressionTree? = nil) {
self.data = data
self.left = left
self.right = right
}
}
class ExpressionTreeLeaf: ExpressionTree {
init(_ n: Int) {
super.init(data: "\(n)") // <----- here!
}
}
The constructors of ExpressionTree
won't be inherited by ExpressionTreeLeaf
in this case, just like in your C# code. Though do note that there are conditions under which they are inherited - they are just not satisfied in this case.
This is just my opinion, but I think expression trees are much easier to build (much less code) if you use recursive enums with associated values, rather than inheritance. There is an example right in the Swift Guide. Here's another example that I just came up with:
enum BinaryOperator {
case plus, minus, times, divide // and more...
}
enum UnaryOperator {
case plus, minus // and more...
}
indirect enum Expression {
case number(Int)
case binaryOp(Expression, BinaryOperator, Expression)
case unaryOp(UnaryOperator, Expression)
}