Swift

[Swift] for-in 과 forEach

yeggrrr🐼 2024. 5. 21. 09:04
728x90

for-inforEach의 차이점


<Swift Documentation>

For-In Loops

You use the for-in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.

-
배열(array), 숫자 범위(ranges of numbers), 문자열 속 문자(charcters in a string)와 같은 요소들을 for-in loop를 통해 sequence를 반복

▷ array(배열)

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!


▷ dictionary(딕셔너리)

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs

You can also iterate over a dictionary to access its key-value pairs. Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated, and you can decompose the (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop. In the code example below, the dictionary’s keys are decomposed into a constant called animalName, and the dictionary’s values are decomposed into a constant called legCount.

-
딕셔너리를 for-in 구문으로 반복할 때, 튜플로 반환된다. 그리고 명시적으로 명명된 상수인 (key, value)로 분해할 수 있다.
위 예시에서 key는 animalName, value는 legCount이다.

딕셔너리는 순서가 없기 때문에 for-in 구문을 돌릴 때, 순서가 보장되지 않는다.

▷ numeric ranges(숫자 범위)

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

범위 연산자(...)를 사용하면, 범위 끝까지 도달할 때까지 반복해서 호출된다. index는 루프가 반복될 때마다 자동으로 설정되는 상수이다. 그래서 각 시퀀스 값이 필요하지 않으면, 변수 이름 대신 underScore(_)를 사용하여 무시할 수 있다.


<Swift Documentation>

ForEach

Calls the given closure on each element in the sequence in the same order as a for-in loop.

-
for-in loop로서 동일한 순서로 스퀀스의 각 요소들에 대해 지정된 클로저를 호출한다.

let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"


numberWords.forEach { word in
    print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"

Using the forEach method is distinct from a for-in loop in two important ways:
1. you cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.
2. Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won't skip subsequent calls.

-
forEach 메서드는 for-in loop와 두 가지 측면에서 다른 점이 있다:
1. break 혹은 continue 구문을 사용하여 현재의 클로저를 종료하거나 subsequent 호출를 스킵할 수 없다.
2. 클로저에서 return을 사용하면 외부 스코프가 아닌 현재 호출에서만 종료되며, subsequent 호출을 스킵하지 않는다.

forInLoop / forEach

let Words = ["A", "B", "C"]

func forInLoops() {
    for word in Words {
        print(word)
        if word == "B" { return }
    }
}

forInLoops()
// Prints "A"
// Prints "B"

print("--------")

func forEach() {
    Words.forEach { word in
        print(word)
        if word == "B" { return }
    }
}

forEach()
// Prints "A"
// Prints "B"
// Prints "C"

 

728x90

'Swift' 카테고리의 다른 글

[Swift] CoreData - 공식문서 파헤치기  (4) 2024.12.01
[Swift] 프로퍼티(Property) ② - 타입  (0) 2024.06.04
[Swift] AutomaticDimension  (0) 2024.06.03
[Swift] 프로퍼티(Property) ① - 저장, 연산  (0) 2024.05.28
Swift 언어란?  (0) 2024.02.19