class ImAClass {
init() {}
func wannaPrint(_ str: String) {
print(str)
}
func unknow() {
instanceOne.wannaPrint("hi")
}
}
let instanceOne = ImAClass()
instanceOne.unknow() //hi
let instanceTwo = ImAClass()
instanceTwo.unknow() //hi
i don’t understand this code in swift, i never seen it in any other language, calling a member method inside a class using a specific instance instead self
In this example i just expected to be able to access members through self
>Solution :
The reason why you didn’t see that before is because it’s bad code practice.
But what is happening here is that instanceOne and instanceTwo are 2 global variables.
Therefore they are available from everywhere in your application.
Now that you can access them from anywhere you can access them from inside your class ImAClass.
So in that case the method unknown is using the instance method wannaPrint of the occurence instanceOne.
If the scope of instanceOne changes you will have a compilation error.
If instanceOne is deallocated your app will crash. But in a validity stand point this code is valid.
You can also do something trickier
class ImAClass {
private let str: String
init(str: String) {
self.str = str
}
func wannaPrint() {
print(str)
}
func unknow(){
instanceOne.wannaPrint()
}
}
let instanceOne = ImAClass(str: "Hi")
instanceOne.unknow()
let InstanceTwo = ImAClass(str: "ho")
InstanceTwo.unknow()
This will have the same result as before even tho the text assign to each instance is different. It’s because we use the method wannaPrintof instanceOne therefore with its own str ("Hi")
PS: you can do that in most langage but no-one does.