0

In swift I can create a method like -

#1

func baseURL() -> String {
    #if DEBUG
        return "https://debug.myserver.url.com"
    #else
        return "https://production.myserver.url.com"
    #endif

}

I can also write it in this way -

#2

var baseURL:String {
    #if DEBUG
        return "https://debug.myserver.url.com"
    #else
        return "https://production.myserver.url.com"
    #endif
}

The requirement of declaring a get only property is met by both methods. Personally I find the second method better cos of readablility.

I know its not too much of a difference, but I'd still like to know which one is better? Does either method have any advantage over the other?

Tushar Koul
  • 2,830
  • 3
  • 31
  • 62
  • 5
    "Personally I find the second method better cos of readablility" Then the second one is better. – matt Jun 21 '16 at 16:14
  • 1
    Usually I prefer computed properties because you can call them without the `()`. However IMHO the rule of thumb seems to be: use computed property when you don't have to create complex objects. – Luca Angeletti Jun 21 '16 at 16:22

2 Answers2

5

Does either method have any advantage over the other?

Not internally, no. A computed property is a function, so there is no difference in implementation under the hood.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I agree with Matt. I use vars when doing something that requires almost no work (checking states of variables to see which value should be used) but if you are doing work I recommend creating a func instead. – SierraMike Jun 21 '16 at 16:52
0

If you are simply getting a value with minimal computation, such as your example, then a getter is a good option.

If getting the value could do some heavy computation or modifies any members on the class, then a function is preferable.