Accessing non static constant in static function of swift class

I came across this question on stackoverflow.

https://stackoverflow.com/questions/32346456/accessing-non-static-constant-in-static-function-of-swift-class

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

Your email address will not be published. Required fields are marked *