简体   繁体   中英

Generic Protocol with Associated Type Not Defining Implicitly

I'm trying to implicitly define an associated type however I get an error:

'RowProtocol' is ambiguous for type lookup in this context

protocol RowProtocol {
    associatedtype T
    var cellClass: T.Type { get }
    init(cellClass: T.Type)
}

struct Row: RowProtocol {
    let cellClass: T.Type
    init(cellClass: T.Type) {
        self.cellClass = cellClass
    }
}

You could then initialize it using:

let implicitRow = Row(cellClass: Cell.self)

How can I make this work?

Conformance to RowProtocol requires mapping the associated type T to a concrete type, and Row doesn't do this. I assume you also want to make Row generic, this is why you didn't specify a type alias for T from the protocol.

The solution is to make Row generic also:

struct Row<T>: RowProtocol {
    let cellClass: T.Type
    init(cellClass: T.Type) {
        self.cellClass = cellClass
    }
}

Now the compiler is happy, as it has a concrete type to pass to RowProtocol . Keep in mind though that for the compiler the T from Row is different from the T of RowProtocol , the latter being a protocol requirement while the first being a generic.

// exactly the same struct, but with different name for the generic argument.
struct Row<U>: RowProtocol {
    let cellClass: U.Type
    init(cellClass: U.Type) {
        self.cellClass = cellClass
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM