Search code examples
swiftgetter-settercomputed-properties

Why doesn't Swift use getter and setter for properties as much as Java or C#?


Q1: I am from Java/C# background and learning Swift right now. When I write java or C# code, for every property within the class, I need to write getter and setter. However, I found that we didn't write getter and setter so much in swift. I am curious about why it is.

Q2: I know there are two kinds of properties, stored and computed properties. It seems like we only need to set the getter or setter for computed properties. Is that true?


Solution

  • Java historically had different syntax for direct property access versus a method call that gets the value (a "getter"). Since you might someday want to override a property with a method, for consistency it is common to create a method in all cases.

    Swift avoids this problem by having the same syntax for direct property access and "getters" (computed properties). This means you can change your mind later without impacting callers, and so there is no reason to create a method "just in case."

    A computed property is defined as one with a "getter" (a get method) in Swift.