2017-04-25 85 views
0

是否有一種方法可以使用.enumerated()和stride使用大於1的索引通過字符串數組進行for-in循環,以便保持指數和價值?Swift:For循環通過大於1的索引遍歷枚舉數組

例如,如果我有陣列

VAR testArray2:[字符串] = [ 「一」, 「B」, 「C」, 「d」, 「E」]

和我想通過循環利用testArray2.enumerated(),也使用跨距由2輸出:

0, a 
2, c 
4, e 

所以最好是這樣的;但是,此代碼將不起作用:

for (index, str) in stride(from: 0, to: testArray2.count, by: 2){ 
    print("position \(index) : \(str)") 
} 

回答

4

您有兩種方法可以獲得所需的輸出。

  1. 只使用stride

    var testArray2: [String] = ["a", "b", "c", "d", "e"] 
    
    for index in stride(from: 0, to: testArray2.count, by: 2) { 
        print("position \(index) : \(testArray2[index])") 
    } 
    
  2. 使用enumerated()for inwhere

    for (index,item) in testArray2.enumerated() where index % 2 == 0 { 
        print("position \(index) : \(item)") 
    } 
    
+0

謝謝,我只是在學習Swift,這對我來說都是非常新的語法。 – Biggytiny

+0

@Biggytiny歡迎隊友:)一旦你理解了它的語法,對你來說也很容易。 –

3

要一個箭步迭代,你可以使用一個where條款:

for (index, element) in testArray2.enumerated() where index % 2 == 0 { 
    // do stuff 
} 

另一種可能的方式是從指數映射到索引和值的元組的集合:

for (index, element) in stride(from: 0, to: testArray2.count, by: 2).map({($0, testArray2[$0])}) { 
    // do stuff 
}