M Dabbs
M Dabbs

Reputation: 23

Confused about a variable value?

I'm trying to write a program that tells if a phrase is a palindrome or not. Here is the code the tutorial wants me to produce:

var text = ["h", "e", "l", "l", "o"]
var reversed = [String]()

var counter = text.count - 1

while counter >= 0 {
   reversed.append(text[counter])
   counter -=1
}

I have no idea why I have to add the -1 after I define the counter variable with text.count. Shouldn't the counter -=1 in the while loop be enough?

Upvotes: 2

Views: 39

Answers (1)

Woodstock
Woodstock

Reputation: 22926

This is because arrays in Swift (such as the string array that holds your text) are zero based.

i.e. their first element is at position zero, and last element at position array.count-1.

So when iterating over arrays manually, one wants to iterate between [0] and [array.count-1].

Normally one wouldn't even consider this because you would usually not bother using manual loops and instead use fast enumeration or for in.

e.g.

var text = ["h", "e", "l", "l", "o"]
for letter in text.reversed() {
    print(letter)
}

Upvotes: 1

Related Questions