How to loop through an array from the second element in elegant way using Swift

后端 未结 4 775
无人及你
无人及你 2020-12-21 06:15

I am a beginner of Swift for iOS development, and want to find an elegant way to loop through an array from the second element.

If it is in Objective-C, I think I ca

4条回答
  •  不知归路
    2020-12-21 06:39

    In general, there is a nice pattern for getting a sub-array like this:

    let array = [1, 2, 3, 4, 5]
    array[2..

    Leo's answer is more succinct and a better approach for the case you asked about (starting with the second element). This example starts with the third element and just shows a more general pattern for getting arbitrary ranges of elements from an array and performing an operation on them.

    However, you still need to explicitly check to make sure you are using a valid range to avoid crashing as you noted, e.g.:

    if array.count > 1 {
        array[2..

提交回复
热议问题