I came across this question on stackoverflow.
Basically it asked, how we can access instance members from static functions.
The answer would be no, we can’t access instance variables from static method.
But this is possible using a singleton design pattern. The actual code is shown below
public class Test {
private let testString: String
init(test:String){
testString = test
}
static func Get(url:String){
//Here testString is not accessible..
}
}
This is how I can alter it.
public class Test {
static let shared = Test(test: "redflower")
private var testString: String
private init(test: String){
testString = test
}
static func Get(url:String){
// access the string here
Test.shared.testString = url
}
}
There you go.
Leave a Reply