aleclarson aleclarson - 1 year ago 73
iOS Question

"initialize" class method for classes in Swift?

I'm looking for behavior similar to Objective-C's

class method, in that the method is called once when the class is initialized, and never again thereafter.

A simple
class init () {}
in a
closure would be really sleek! And obviously when we get to use "
class var
s" instead of "
static var
s in a struct closure", this will all match really well!

Answer Source

If you have an Objective-C class, it's easiest to just override +initialize. However, make sure subclasses of your class also override +initialize or else your class's +initialize may get called more than once! If you want, you can use dispatch_once() (mentioned below) to safeguard against multiple calls.

class MyView : UIView {
  override class func initialize () {
    // Do stuff


If you have a Swift class, the best you can get is dispatch_once() inside the init() statement.

private var once = dispatch_once_t()

class MyObject {
  init () {
    dispatch_once(&once) {
      // Do stuff

This solution differs from +initialize (which is called the first time an Objective-C class is messaged) and thus isn't a true answer to the question. But it works good enough, IMO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download