Swift For-Loops

10 / Jul / 2016 by Ashu Baweja 0 comments

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

[code language=”objc”]
// 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)
}
[/code]

  • Looping n times in reverse

[code language=”objc”]
// output is 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
for i in (1…10).reverse() {
print(i)
}
[/code]

  • Looping through Array Values

[code language=”objc”]
// output is: ashu, amit, deepak
let namesArray = ["ashu", "amit", "deepak"]
for name in namesArray {
print(name)
}
[/code]

  • Looping through Dictionary Values

[code language=”objc”]
// 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&quot": "software development"]
for (key,value) in infoDict {
print("key is \(key) & value is \(value)")
}
[/code]

  • Looping Through an Array with Index

[code language=”objc”]
// 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)")
}
[/code]

Congratulations! you have learned Swift for-loops!!!!!

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *