Mis à jour pour Swift 3
La réponse ci-dessous est un résumé des options disponibles. Choisissez celui qui correspond le mieux à vos besoins.
reversed: nombres dans une plage
Vers l'avant
for index in 0..<5 {
print(index)
}
// 0
// 1
// 2
// 3
// 4
En arrière
for index in (0..<5).reversed() {
print(index)
}
// 4
// 3
// 2
// 1
// 0
reversed: éléments dans SequenceType
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Vers l'avant
for animal in animals {
print(animal)
}
// horse
// cow
// camel
// sheep
// goat
En arrière
for animal in animals.reversed() {
print(animal)
}
// goat
// sheep
// camel
// cow
// horse
reversed: éléments avec un index
Parfois, un index est nécessaire lors de l'itération dans une collection. Pour cela, vous pouvez utiliser enumerate(), qui renvoie un tuple. Le premier élément du tuple est l'index et le deuxième élément est l'objet.
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Vers l'avant
for (index, animal) in animals.enumerated() {
print("\(index), \(animal)")
}
// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat
En arrière
for (index, animal) in animals.enumerated().reversed() {
print("\(index), \(animal)")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
Notez que comme Ben Lachman l'a noté dans sa réponse , vous voulez probablement faire .enumerated().reversed()plutôt que .reversed().enumerated()(ce qui ferait augmenter les indices).
foulée: chiffres
Stride est un moyen d'itérer sans utiliser de plage. Il existe deux formes. Les commentaires à la fin du code montrent ce que serait la version de la plage (en supposant que la taille d'incrémentation est de 1).
startIndex.stride(to: endIndex, by: incrementSize) // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex
Vers l'avant
for index in stride(from: 0, to: 5, by: 1) {
print(index)
}
// 0
// 1
// 2
// 3
// 4
En arrière
Changer la taille d'incrément en -1vous permet de revenir en arrière.
for index in stride(from: 4, through: 0, by: -1) {
print(index)
}
// 4
// 3
// 2
// 1
// 0
Notez la différence toet through.
stride: éléments de SequenceType
Avancer par incréments de 2
let animals = ["horse", "cow", "camel", "sheep", "goat"]
J'utilise 2dans cet exemple juste pour montrer une autre possibilité.
for index in stride(from: 0, to: 5, by: 2) {
print("\(index), \(animals[index])")
}
// 0, horse
// 2, camel
// 4, goat
En arrière
for index in stride(from: 4, through: 0, by: -1) {
print("\(index), \(animals[index])")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
Remarques