Aaron Bratcher
Aaron Bratcher

Reputation: 6451

Why do I need to specify the object type twice?

Give this method signature that's an extension of a protocol:

loadObjectFromDB<T: DBObject>(_ db: ALBNoSQLDB, for key: String, queue: DispatchQueue? = nil, completion: @escaping (T) -> Void) -> DBCommandToken?

Why can't I call it like this? (Category is a struct that adheres to the protocol)

let token = Category.loadObjectFromDB(db, for categoryKey) { (category) in
    // use category object
}

I get a compilation error saying generic parameter T could not be inferred and I have to specify the type again in what is in the execution block:

let token = Category.loadObjectFromDB(db, for categoryKey) { (category: Category) in
    // use category object
}

Upvotes: 0

Views: 56

Answers (1)

EmilioPelaez
EmilioPelaez

Reputation: 19884

Because T's only constraint is that it's a DBObject, the compiler doesn't know anything else about it. If it was constrained to Self instead, then you wouldn't have to explicitly state the type.

Upvotes: 1

Related Questions