Swift - Custom Type Generics


Generics creates code that doesn't need to know precisely what information it's dealing with.

Swift Arrays are generics.

To create a generic type, name your object as usual, and then add a placeholder type name between angle brackets.

T is traditionally the term used, but you can put anything you like.

For example, to create a generic Tree object that contains a value and any number of child Tree objects:


class Tree <T> { 
    var value  : T 
    private (set) var children  : [Tree <T>] = [] 
    init(value  : T) { 
        self.value = value 
    } /*from  w  w w  .j ava  2s  .c  o  m*/
    func addChild(value  : T) -> Tree <T> { 
        let newChild = Tree<T>(value: value) 
        return newChild 

Once a generic type is defined, you can create a specific, nongeneric type from it.

For example, the Tree generic type just defined can be used to create a version that works with Ints and one that works with Strings:

// Tree of integers 
let integerTree = Tree<Int>(value: 5) 

// Can add children that contain Ints 
integerTree.addChild(value: 10) 
integerTree.addChild(value: 5) 

// Tree of strings 
let stringTree = Tree<String>(value: "Hello") 

stringTree.addChild(value: "Yes") 
stringTree.addChild(value: "Internets") 

Related Topics