1

I'm playing with the swift language and i have a question on get/set properties. I think that it makes no sense to let the inner variable be public when the value is managed by a computed property. So I think that making this private to the class is a good practise. As I'm still learning maybe some of you could give me other ideas to leave it public.

class aGetSetClass{

    private var uppercaseString : String

    var upperString : String {
        get {
            return uppercaseString
        }
        set (value) {
            self.uppercaseString = value.uppercaseString
        }
    }

    init(){
        uppercaseString = "initialized".uppercaseString
    }

}


var instance3 = aGetSetClass()
println(instance3.upperString) // INITIALIZED
instance3.upperString = "new"
// println(instance3.uppercaseString) // private no access
println(instance3.upperString) // NEW
instance3.upperString = "new123new"
println(instance3.upperString) // NEW123NEW
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
Guyvo
  • 171
  • 1
  • 5
  • Is your question whether this is a good practice or not? – David Rönnqvist Jul 31 '15 at 12:42
  • What design pattern looks like a custom setter: you modify the new value of the property (make it uppercase) before storing it. That's the right way to do it in Swift. See also this question: http://stackoverflow.com/questions/25828632/swift-custom-setter-on-property – Code Different Jul 31 '15 at 14:03
  • Thanks Zoff. @David yes I asked me that question indeed. Because in this simpel example suppose you let it public everyone that uses the classes can modify the value with or without uppercase forcing. But maybe there are some cases letting it public make sense, although I can not think of one directly. But there must be at least a reason why this is implemented like this in Swift core. – Guyvo Jul 31 '15 at 16:19

1 Answers1

0

The only way I could think of public access is either to make it as private set and then use a public set function instead:

public private(set) uppercaseString: String

public func setUpperString(string: String) {
    uppercaseString = string.uppercaseString
}

Or make it public and use a didSet which sets itself under a certain condition (very inefficient for long strings):

public uppercaseString: String {
    didSet {
        if uppercaseString != uppercaseString.uppercaseString {
            uppercaseString = uppercaseString.uppercaseString
        }
    }
}

These implementations use direct public access but your version is in my perspective the better / "swifter" way.

Qbyte
  • 12,753
  • 4
  • 41
  • 57