Search code examples
swiftgetter-setter

Different between getters and func getSomething()?


what is the different between getter of mFirstName variable, and instance method getFirstName()? If i have the first, why do i need another get method?


Solution

  • The getter of the variable is always executed. The only exception to that is when you get or set variables inside of init. This is the swift way of implementing getters and setters. Languages like Java do not have this option so you have to create getter and setter functions.

    IMO providing getters and setters on your variable is safer. This way you ensure that they are always called. If you have getter and setter functions and modify a variable directly and forget to call the setters and getters it can lead to weird errors.