0xSina
0xSina

Reputation: 21553

How do I call a static function of a class by its instance

I have a simple class:

class TableItem {
  class func cellIden() -> String {
    return "TableItem"
  }
}

and a subclass of TableItem

class EditableItem {
  override class func cellIden() -> String {
    return "EditableItem"
  }
}

Then, somewhere in my code, I have this:

var items: [TableItem] = [TableItem(), EditableItem()]

Now, what I want to do is, iterate through items and call each TableItem's static cellIden() function.

for i in items {
  var iden = i.self.cellIden()
}

However, it tells me TableItem does not have a member called 'cellIden'

How can I call the static method of a class from its instance?

Note: I can't call TableItem.cellIden() because i can be a TableItem or an EditableItem

Upvotes: 2

Views: 84

Answers (2)

Grimxn
Grimxn

Reputation: 22487

Since you wish to interrogate an instance, rather than the class, you could provide an instance method (that would return the class's method). You need only do it in the base class, and this hides the implementation from the user ...

class TableItem {
   class func cellIden() -> String {
       return "TableItem"
   }

   func iCellIden() -> String {
       return self.dynamicType.cellIden()
   }
}

class EditableItem: TableItem {
   override class func cellIden() -> String {            
       return "EditableItem"
   }
}

var items: [TableItem] = [TableItem(), EditableItem()]

for i in items {
    println("\(i.dynamicType.cellIden())") // Works, fine
    println("\(i.iCellIden())") // Equivalent, but removes responsibility from calle
}

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385500

You need to get the runtime type of i. Every instance has a dynamicType property that returns its runtime (dynamic) type:

var iden = i.dynamicType.cellIden()

It's documented in The Swift Programming Language: “Dynamic Type Expression”.

Upvotes: 2

Related Questions