for loops
The for-in loop iterate over ranges of numbers, characters in a string, items in an array or a dictionary.
ranges of numbers
for count in 1...4 {
println("count = \(count)")
}
//Console output:
count = 1
count = 2
count = 3
count = 4
var sum = 0
for count in 1...4 {
sum += count
println("sum = \(sum)")
}
//Console output:
sum = 1
sum = 3
sum = 6
sum = 10
Characters in a string
for myChar in "ABCDE" {
println("\(myChar)")
}
//Console output:
A
B
C
D
E
Items in an array
http://studyswift.blogspot.tw/2014/06/arrays-dictionaries.html
Items in a dictionary
http://studyswift.blogspot.tw/2014/07/dictionaries.html
C-type for loop
for var count = 1; count < 5; count++ {
println("count = \(count)")
}
//No ( )
//Console output:
count = 1
count = 2
count = 3
count = 4
while loops
while loops
var i = 0
while i++ < 5 {
println("\(i)")
}
//Console output:
1
2
3
4
5
do-while
6
5
4
3
2
1
do-while
do {
println("\(i--)")
} while i > 0
//Console output:6
5
4
3
2
1
No comments:
Post a Comment