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

后端 未结 4 686
无人及你
无人及你 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:31

    you can also use custom subscript to make sure you avoid crashing

    extension Array {
        subscript (gurd index: Index) -> Array.Element? {
            return (index < self.count && index >= 0) ? self[index] : nil
        }
    }
    

    use example:

    let myarray = ["a","b","c","d","e","f","g","h"]
    
     for i in -15...myarray.count+20{
                print(myarray[gurd: i])
            }
    
    0 讨论(0)
  • 2020-12-21 06:36
      if array.count>=2 {
         for n in 1...array.count-1{
             print(array[n])   //will print from second element forward 
          }
     }
    
    0 讨论(0)
  • 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..<array.count].forEach {
        print($0)     // Prints 3, 4, 5 (array from index 2 to index count-1)
    }
    

    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..<array.count].forEach {
            print($0)
        }
    }
    
    0 讨论(0)
  • 2020-12-21 06:51

    You can use your array indices combined with dropfirst:

    let array = [1,2,3,4,5]
    
    for index in array.indices.dropFirst() {
        print(array[index])
    }
    

    or simply:

    for element in array.dropFirst() {
        print(element)
    }
    
    0 讨论(0)
提交回复
热议问题