Loop

권현석·2023년 1월 16일
0

for in Loop

let names = ["Alex", "Amy", "Mallory", "Mathew"]
for name in names {
	print("Hello, \(name)!")
}
// Hello Alex!
// Hello Amy!
// Hello Mallory!
// Hello Mathew!

여기서 'name'은 새로운 상수가 되고 for 루프에 의해 names array의 구성요소 숫자만큼 for 루프 안의 코드가 실행된다.
그리고 상수 'name'에 'names' Array의 구성요소들을 할당한다.

for Loop with range

for number in 1...5 {
	print("Hello, \(number)")
}
// Hello 1
// Hello 2
// Hello 3
// Hello 4
// Hello 5 

만일 'in' 다음에 오는 sequence를 사용하지 않으면

for _ in 1...5 {}

와 같이 변수이름을 쓰는 대신에 '_'를 사용해 코드를 쓸 수 있다.

Practice

let fruits = ["apple", "pear", "oragnge"]
let contacts = ["Alex": 123456, "Amy": 789012, "Mallory": 345678]
let word = "extraordinary"
let halfOpenRange = 1..<5
let closedRange = 1...5
  • 'let fruits: Set'으로 하면 array의 구성요소가 임의의 순서로 print되고, 'let fruits: Array'으로 하면 array의 구성요소 순서대로 print된다.
  • 'contacts는 dictionary인데 이는 'key: value'로 구성되므로 사람이름을 print하려면 'print(for 루프의 상수이름.key)', 전화번호를 print하러면 'print(for 루프의 상수이름.value)'를 하면 된다.
  • 'word'의 경우 for 루프에 넣으면 글자 수 만큼 for 루프가 실행된다.
  • 'halfOpenRange', 'closedRange'의 경우 해당 범위의 숫자만큼 루프를 실행하고 싶은 경우 for 루프의 상수이름 자리에 '_'를 작성하고 실행할 코드를 작성하는 위치에 해당범위의 숫자 이외의 다른 코드를 작성하면 된다.

while Loop

while conditionIsTrue {
	implement
}

위의 경우 'conditionIsTrue'에 어떠한 조건이 들어가고 이 조건이 참이면 implement는 조건이 거짓이 될때까지 계속 반복실행된다.

profile
wanna be an iOS developer

0개의 댓글