Reputation: 11633
I have this swift code :
protocol Table {
static var tableName: String { get }
}
class User: Table {
internal static var tableName = "user"
}
I know would like to construct methods with Table
protocol parameters.
Something like :
func doSomethingFrom(table: Table) {
print(table.tableName)
}
doSomethingFrom(table: User) // prints "user"
Is there a way to achieve this simply ?
Upvotes: 0
Views: 506
Reputation: 1
Since the value of tableName will be the same for all instances of User (because it is static) you can do:
func doSomethingFrom(table: Table) {
print(User.tableName)
// OR:
print(type(of: table).tableName)
}
Make sure though this is what you really want.
Upvotes: 0
Reputation: 299265
This is the syntax you're looking for. You need to pass the type itself by appending .self
. This is to prevent mistakes (since talking about types directly is kind of rare, but easy to do by accident). And you need to take a parameter of the type itself rather than an instance of that type.
func doSomethingFrom(table: Table.Type) {
print(table.tableName)
}
doSomethingFrom(table: User.self) // prints "user"
Upvotes: 2