UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Watching Swift in One Hour - question about extension

Forums > Swift

Hi, one thing about extension and the "var" example in the video is not clear to me. Consider this code:

extension String{

    func lines() -> [String] {
        print("calculating lines")
        return self.components(separatedBy: CharacterSet.newlines)
    }
    var linesVar : [String] {
        print("calculating linesVar")
        return self.components(separatedBy: CharacterSet.newlines)
    }
}

I tried then, to do some printing:

    let lyrics = """
    I'm walkin' downtown
    No lookin' around
    'Cause I'm a fool and a half
    Blessed and beaten by love
    """
    print(lyrics.lines().count)
    print("again")
    print(lyrics.lines().count)

    print(lyrics.linesVar.count)
    print("again")
    print(lyrics.linesVar.count)

In both cases, the printout "calculating lines"/"calculating linesVar" is called every time, the same thing happens in both instances, i.e. a method is called on self and the result passed on.

So, is there technically any difference between declaring it as a var or as a func()? To me, func() is clearer, since it in reality doesn't seem to be a var? It's just a method returning the value of an examination of the String.

Pointers appreciated.

2      

Mathias is philosophical:

is there technically any difference between declaring it as a var or as a func()?
To me, func() is clearer, since it in reality doesn't seem to be a var?

Keep asking questions!

I see this the opposite way.

I think of a function as a way to perform a series of manipulations, or transitions. For example you may use a function to remove the letter "T" from a string, or test some data to see if it meets some criteria or contains certain data, resulting in a boolean. Additionally, you may use a function to transform string data into ascii values.

On the otherhand, I think of a variable (var) as a box that holds a value.

 // vars hold values
 let numberOfPurpleLightSabers =  2
 let ultimateAnswer            = 42

I think of a computed var as a box that holds a value, but may need a bit of calculation to get there. This is fine with me because I don't need to have another var in my code that has to be updated whenever a related var in my code changes. It's this dependency that makes computed vars so powerful.

If you change a value of one var, it can affect the results in other parts of your application.

// Some game variables
let numberOfHands = 42
var currentHand   = 15
var gameOver: bool {
    currentHand >= numberOfHands  // excellent! keep gameOver in sync with your game state
}

// don't do this!
var gameOver = false
// overlooking this may cause your gameOver var to get out of sync with your game state.
gameOver = checkIfOver(current: currentHand, max: numberOfHands) // not cleaner code, imho.

I think the computed var, in many cases, is much easier to maintain and use.

These are just my thoughts.

2      

Hello Obelix thanks for responding. Yes indeed i suppose it's philosophical in a sense.

What it boils down to, to me, is in your response:

"I think of a computed var as a box that holds a value" - but there IS no "box" in the struct, the value is calculated and returned and then forgotten about - it is not remembered anywhere in the struct. The next time i call that "var", it is calculated again, even though nothing else has changed. What if it's a super complex calculation going on inside that function? I might call it many times, perhaps with no other parameter has changed since i think its just a field, slowing stuff down unneccesarily. One simple example would be logging - some one might use the "var" twice - first to just log it, and then to actually use it.

If it's instead declared as a function, i know that and can save the calculation somewhere else and then re-use it as needed.

That's why it, to me, doesn't really make sense to declare it as a var field on the extension (I have the exact same conundrum when it comes to structs).

To each his own i guess :) I am just starting to learn Swift as you might guess, and coming from other languages i've spent many many years with it's much to wrap your head around. It seems that these computed properties are used a bit in Swift (as Paul said in his video), so i guess i'll just have to accept it.

Again, thanks for chipping in and sorry if the response was too long...

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.