Vincent Saluzzo Vincent Saluzzo - 6 months ago 36
Swift Question

Class variables not yet supported

I begin my project with a split view controller as initial view controller and start it automatically from storyboard.

Generally, an app with this UI have one and only one split view controller as root, so I create a static variable in the subclass and set it when initialisation was done.

So I want try this behaviour with swift.

I read the Swift programming language guide book on iBook about Type properties (with static and class keyword) and trying a piece of code to the job:

import UIKit

class SplitViewController: UISplitViewController {

class func sharedInstance() -> SplitViewController {
return SplitViewController.instance
}

class let instance: SplitViewController = nil

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initialization()
}

init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder);
self.initialization()
}

func initialization() {
SplitViewController.instance = self;
}
}


but I figured out when Xcode say the class keyword for type properties wasn't supported yet.

error detail in image

Did you have a solution to do this ?

Answer

Swift now has support for static variables in classes. This is not exactly the same as a class variable (because they aren't inherited by subclasses), but it gets you pretty close:

class X {
  static let y: Int = 4
  static var x: Int = 4
}

println(X.x)
println(X.y)

X.x = 5

println(X.x)
Comments