OvRdose OvRdose - 3 months ago 6
Swift Question

Using func() in seperate class requires instance of the class that owns the method

Sorry if this is a stupid question but when I try to use a function in another class it requires an instance of the class that owns it.

class Economy {

let configuration = NSUserDefaults.standardUserDefaults()

func setBalance(amount: Double) {
configuration.setDouble(getBalance(), forKey: "balance")
}

func getBalance() -> Double {
return configuration.doubleForKey("balance")
}
}


When I use the getBalance() method in the setBalance method it works fine but when I use it to define a variable that isn't in a method or use it in another class I have to do:
getBalance(self: Economy)
instead of just
getBalance()

I'm not sure if this is a problem or what but how can I fix this?

Answer

It looks, from your comments, as if you don't really want a class (with different instances) at all : "I just want a way to be able to use the methods". This is not usual in classes - usually, a class instance holds its own unique state information. In your case, though, all instances will hold the same state (the standardUserDefaults).

There are two ways to do what you want - use a singleton, or, more simply, use naked functions:

func setBalance(amount: Double) {
    let configuration = NSUserDefaults.standardUserDefaults()
    configuration.setDouble(getBalance(), forKey: "balance")
}

func getBalance() -> Double {
    let configuration = NSUserDefaults.standardUserDefaults()
    return configuration.doubleForKey("balance")
}

note, these are outside any class. Then you simply say

setBalance(15)
print("\(getBalance()") // prints 15

I feel I have to add, though, that using NSUserDefaults in this way is probably not to be recommended - you are really creating a global variable by the back door.

Comments