Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling a member method inside a class using a specific instance instead self

image

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading