Generic Class Examples

suggest change

A generic class with one type parameter:

class Box<T> {
    var value: T
    init(value: T) {
        self.value = value
    }
}

Create objects by choosing that parameter:

let words = Box(value: "swift") // Box<String>
let numbers = Box(value: 1)     // Box<Int>

A generic class can take more than one type parameter:

class Trio<A, B, C> {
    var first: A
    var second: B
    var third: C
    init(first: A, second: B, third: C) {
        self.first = first
        self.second = second
        self.third = third
    }
}

Use it the same way:

let mixed = Trio(first: "swift", second: 1, third: 1.5) // Trio<String, Int, Double>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents