0

so I have an array and I want to add 1 to all the items.

var arr = [2, 3, 6, 9]

for (index, x) in enumerate(arr) {

    arr[index] = arr[index] + 1

}

is there a simpler version of this? there's no reason to have 'x' in there. I know there's the alternate way of writing it this way:

arr[index] = x + 1

but that doesn't seem like enough reason to have 'x' there.

2 Answers 2

2

You can iterate indices of the array

var arr = [2, 3, 6, 9]

for index in indices(arr) {
    arr[index] += 1
}

Essentially, indices(arr) is the same as arr.startIndex ..< arr.endIndex, but it's simple :)

OR, in this specific case, you might want to:

arr = arr.map { $0 + 1 }
Sign up to request clarification or add additional context in comments.

2 Comments

I've just started learning swift, but the .map function and how simple it is makes more sense to me. i'm not sure what indices is and what limitations it has over enumerate (or how it's better) but thanks for the reply :)
taking the map function a bit further I realized it's also possible to do these: arr = arr.map { $0 * $0 + (2 * $0) }
1

Yes, this is a really good use case for the .map function.

var arr = [2, 3, 4]
arr = arr.map({$0 + 1})
// arr would now be [3, 4, 5]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.