L8NIT3TR0UBL3
L8NIT3TR0UBL3

Reputation: 101

Learning swift, Issues with incrementing variables

I'm back again with what is likely a simple issue, however its got me stumped.

I've written very small, very basic piece of code in an xcode playground. My code simply iterates over a function 10 times, printing the output each time.

var start = 0
var x = 0
var answer = 2 * x

func spin() {
    print(answer)
}
while start < 10 {
    spin()
    x++
    start++
}

Now for my issue, It seems my code properly increments the 'start' variable.... running and printing 10 times. However it prints out a list of 0's. For some reason the 'x' variable isn't incrementing.

I've consulted the few ebooks I have for swift, aswell as the documentation, and as far as i can see my code should work.

Any ideas?

P.s. As per the documentation I have also tried ++x, to no avail.

edit

Updated, working code thanks to answers below:

var start = 0
var x = 0
var answer = 2 * x

func spin() {
    print("The variable is", x, "and doubled it is", answer)
}
while start <= 10 {
    spin()
    x++
    start++
    answer = 2 * x
}

Upvotes: 1

Views: 266

Answers (2)

cezheng
cezheng

Reputation: 564

You have just assigned 2 * x to answer at the beginning of the program, when x == 0, and the value of answer remains its initial value through out the program. That's how Value Types work in Swift as well as in almost any other languages

If you wish to always have answer to be 2 times of x, you should write like this

var start = 0
var x = 0
var answer = 2 * x

func spin() {
    print(answer)
}
while start < 10 {
    spin()
    x++
    start++
    answer = 2 * x
}

And thanks to Leo Dabus's answer, you may also define a Computed Property to caculate the value of 2 * x each time you try to get the value of answer. In this way, answer becomes readonly and you cannot assign other values to it. And each time you try to get the value of answer, it performs the 2 * x calculation.

var start = 0
var x = 0
var answer: Int {
  return 2 * x
}

func spin() {
    print(answer)
}
while start < 10 {
    spin()
    x++
    start++
}

Upvotes: 4

Leo Dabus
Leo Dabus

Reputation: 236360

What you need is a read only computed property. Try like this:

var answer: Int { return  2 * x }

Upvotes: 3

Related Questions