Reshad Reshad - 6 months ago 10
Swift Question

Can not use a singleton class to return its properties

Hello Guys I have the following code

class DeviceListViewController {
private var currentPeripheral:BLEPeripheral?

public class var sharedInstance: DeviceListViewController {
struct Singleton {
static let instance = DeviceListViewController()
}
return Singleton.instance
}

func getCurrentPeripheral() -> BLEPeripheral? {
return currentPeripheral
}

}


But when I use this in another class like following

DeviceListViewController.getCurrentPeripheral()


it gives me an error telling me the following
Use of instance member "getCurrentPeripheral" on type "DeviceListViewController"; did you mean to use a value of type "DeviceListViewController" instead?

I have no clue what I am doing wrong here. Any suggestions on how to solve this?

p.s. the autocomplete function of xcode passes the ViewController as parameter along with it somehow

DeviceListViewController.getCurrentPeripheral(DeviceListViewController)


But it results in the same error

Answer

You need to call the method on the shared instance, not on the class

DeviceListViewController.sharedInstance.getCurrentPeripheral()