Search code examples
swiftclassgenericsnested-generics

Generic of Generics ? class A<T<U>>?


Can I somehow force the generic type to have a generic type ? I want to have some functions, that have as a parameter type U, so how can I do that ?

Code:

class TableViewViewModel<T<U>> {
    typealias SectionDataType = T
    typealias RowDataType = U

    var sections = [SectionDataType<RowDataType>]()
}

Solution

  • Try declaring a protocol SectionDataType that requires an associated type. This means that any conforming type (like Section below) must implement a typealias. Then, in TableViewViewModel you can access the type which you were calling U through that typealias.

    protocol SectionDataType {
        associatedtype RowDataType
    }
    
    struct Section<U>: SectionDataType {
        typealias RowDataType = U
    }
    
    class TableViewViewModel<T: SectionDataType> {
        typealias RowDataType = T.RowDataType
    
        var sections = [T]()
    }