Reputation:
I don't quite understand when to state Tree<T>
and when just T
class Tree<T> {
var value: T
private (set) var children: [Tree<T>] = []
init(value: T) {
self.value = value
}
func addChild(value: T) -> Tree<T> {
let newChild = Tree<T>(value: value)
children.append(newChild)
return newChild
}
}
Upvotes: 0
Views: 46
Reputation: 54775
The <T>
makes Tree
a generic type and declares the generic type parameter called T
. If you want to declare a property as type Tree
, you need to write it as Tree<T>
. However, if you want to use the type of a tree node, then you need to use T
.
When you declare value
, you simply want to store the generic value, so its type needs to be T
. However, the children
array stores an array of trees, so you need to declare it as [Tree<T>]
, not just [T]
.
For each instance of Tree
, the generic type parameter T
might be different. By naming the generic type parameter something more meaningful, such as Value
, this will become much more clear.
class Tree<Value> {
var value: Value
private (set) var children: [Tree<Value>] = []
init(value: Value) {
self.value = value
}
func addChild(value: Value) -> Tree<Value> {
let newChild = Tree<Value>(value: value)
children.append(newChild)
return newChild
}
}
let intTree = Tree(value: 1) // `Value` is of type `Int` here, but you don't need to specify it, the compiler can infer it
let stringTree = Tree(value: "value") // `Value` is of type `String` here
Upvotes: 1