Swift For-Loops
In Swift 3.0 C-style for-loops will be removed. This will force developers to use a swift syntax for for-loops. So lets begin with swift for loops :
- Looping n times
// output is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for i in 0..<10 { print(i) } // or for i in 0...9 { print(i) }
- Looping n times in reverse
// output is 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 for i in (1...10).reverse() { print(i) }
- Looping through Array Values
// output is: ashu, amit, deepak let namesArray = ["ashu", "amit", "deepak"] for name in namesArray { print(name) }
- Looping through Dictionary Values
// output is key is age & value is 24, key is profession & value is software development, key is name & value is ashu let infoDict = ["name": "ashu", "age": "24", "profession"": "software development"] for (key,value) in infoDict { print("key is \(key) & value is \(value)") }
- Looping Through an Array with Index
// output is index: 0 & value: ashu, index: 1 & value: amit, index: 2 & value: deepak let namesArray = ["ashu", "amit", "deepak"] for (index,name) in namesArray.enumerate() { print("index: \(index) & value: \(name)") }
Congratulations! you have learned Swift for-loops!!!!!