2

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

newacct
  • 119,665
  • 29
  • 163
  • 224
0xSina
  • 20,973
  • 34
  • 136
  • 253
  • Almost duplicate of [Access class property from instance?](http://stackoverflow.com/questions/24309458/access-class-property-from-instance) (which is about type properties instead of type methods). – Martin R May 31 '15 at 17:26

2 Answers2

2

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”.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

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
}
Grimxn
  • 22,115
  • 10
  • 72
  • 85
  • That's not what I want to do though. I want a static function because cellIden is independent of any instance and it needs to be called before the instantiation of a cell. – 0xSina May 31 '15 at 19:00
  • It calls the class function, which will return the correct string for the class / subclass. It just hides the implementation from the caller. – Grimxn Jun 01 '15 at 08:50
  • Maybe, but not the proper way of doing it. Thanks anyways. – 0xSina Jun 01 '15 at 12:50