Reputation: 37581
I'm trying to declare a class which has a static variable which I want to set to an object of the class i.e.
class MyViewController: UIViewController {
@IBOutlet weak var title: UILabel!
static var staticSelf:MyViewController
This declaration generates the following error:
"class var declaration requires an initializer expression or getter/setter specifier".
So I tried several attempts at adding an initialzer but just was getting more or different compilation errors. So instead I tried adding a getter/setter specifier as it says in the error, but this is resulting in an infinite loop when run. I've tried several versions, this is the latest:
class MyViewController: UIViewController {
@IBOutlet weak var title: UILabel!
static var staticSelf:MyViewController {
set (selfInstance) {
MyViewController.staticSelf = selfInstance
}
get {
return MyViewController.staticSelf
}
}
override func viewDidLoad() {
super.viewDidLoad()
MyViewController.staticSelf = self
}
}
The initial attempt at the implementation of the setter method was staticSelf = selfInstance
, XCode flagged this as an error and auto-corrected to self.staticSelf = selfInstance
, but that results in an infinate loop, so I changed it to MyViewController.staticSelf = selfInstance
, but that too creates an infinate loop.
I've tried a thousand things to get this set up and could have done it in 3 seconds with objective-C , and am getting very fed up with Swift right now.
Upvotes: 7
Views: 24689
Reputation: 4219
Assuming that in objective-c you would have used a pointer that could be null, in Swift, you do something similar.
class MyViewController: UIViewController {
static var staticSelf:MyViewController?
override func viewDidLoad() {
super.viewDidLoad()
MyViewController.staticSelf = self
}
func somefunc() {
}
}
When you need to access it from elsewhere:
if let controller = MyViewController.staticSelf {
controller.somefunc()
}
Upvotes: 4
Reputation: 130082
The basic example
class MyClass {
static var string: String
}
does not work because unitialized variables have nil
value. However, in Swift you can assign nil
only to optional variables.
You have two options:
Declare the variable as optional
static var string: String?
or
static var string: String? = nil
Initialize with a non-nil value:
static var string: String = "some value"
If your aim is to create a singleton, then see the official Apple guide for the solution:
class MyViewController: UIViewController {
static let staticSelf = MyViewController()
}
Upvotes: 14
Reputation: 650
You need to assign the value right away in the declaration line:
static var staticSelf = MyViewController()
This is, btw. the standard pattern to create a singleton in Swift.
Upvotes: 3