Pierre Pierre - 2 months ago 8
Swift Question

Protocol static var used in method

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 ?

Answer

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"
Comments