Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static member cannot be used on instance of type

Tags:

swift

I am attempting to create an access method to a singleton. I am getting this error (see code below). I don't understand why I am getting this error and what this error means. Can anyone explain?

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {   static private var thedelegate: AppDelegate?    class var delegate : AppDelegate {     return thedelegate!   }    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {     thedelegate = self // syntax error: Static member 'thedelegate' cannot be used on instance of type 'AppDelegate' 
like image 865
andrewz Avatar asked Mar 09 '16 18:03

andrewz


2 Answers

You need to prepend the static/class variable or function with the class name in which it is declared, even when in that same class.

In this case, you want to return AppDelegate.thedelegate!

and, as Martin R. points out, AppDelegate.thedelegate = self

like image 67
bjc Avatar answered Sep 17 '22 09:09

bjc


You are trying to access Class level variable from the instance of that class. To use that you need to make Class level function: static func (). Try this:

static func sharedDelegate() -> AppDelegate {     return UIApplication.sharedApplication().delegate as! AppDelegate } 
like image 39
Sasha Kozachuk Avatar answered Sep 21 '22 09:09

Sasha Kozachuk