IOS/Swift 문법

4. Control Flow

Hoya0415 2016. 5. 20. 09:30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//: Playground - noun: a place where people can play
 
import UIKit
 
var age = 0
 
while age < 5
{
    print(age)
    age++
}
 
for var age2 = 0; age2<=5; age2++
{
    print("age2 : \(age2)")
}
 
for _ in 1...5{
    print("5")
}
 
for number in 1...5{
    print(number)
}
 
for name in ["Anna""Alex","Brian","Jack"]
{
    print("hello, \(name)")
}
 
for (animalName, legs) in ["ant":6,"snake":0,"cheetah":4]
{
    print("\(animalName)'s have \(legs) legs")
}
 
for index in 1...5 {
    
    print("\(index) items 5 is \(index * 5)")
    
}
cs

for-In Loops structure :

Closed range operator(...)

for index in 1...5 {
    
    print("\(index) items 5 is \(index * 5)")
    
}

underscore character ( _ ) : don't provide  access to the current value during each iteration of the loop

for _ in 1...5{
    print("5")
}
 

for-in loop with an array to iterate over its 

1
2
3
4
for name in names
{
    print("Hello, \(name)!")
}
cs

You can also iterate over a dictionary to access its key-value pairs

1
2
3
4
5
6
let numberOfLegs = ["spider":8,"ant":6,"cat":4]
 
for(animalName, legCount) in numberOfLegs
{
    print("\(animalName)s have \(legCount) legs")
}
cs