简体   繁体   中英

how to simplify array enumerations in swift

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.

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 }

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM