Pierre Pierre - 3 months ago 13
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
protocol parameters.
Something like :

func doSomethingFrom(table: Table) {

doSomethingFrom(table: User) // prints "user"

Is there a way to achieve this simply ?


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) {

doSomethingFrom(table: User.self) // prints "user"