iOS/Swift

[Swift] 배열 순회시 index도 같이 조회하고 싶다면? > enumerated()

임구마🍠 2024. 7. 5. 23:41

배열을 돌 때 우리는 index 정보도 같이 필요한 경우가 있다.

이때 enumerated를 사용하면 된다!

 

 

리턴 값은 시퀀스가 리턴된다고 합니당

 

사용법은 아래와 같다.

 

1. for-in 반복문

let array = ["one", "two", "three"]
for (index, value) in array.enumerated() {
    print("index: \(index), value: \(value)")
}
// Prints "index: 0, value: one"
// Prints "index: 1, value: two"
// Prints "index: 2, value: three"

 

 

2. forEach 반복문

let array = ["one", "two", "three"]
array.enumerated().forEach { print("index: \($0.offset), value: \($0.element)") }
array.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }
// Prints "index: 0, value: one"
// Prints "index: 1, value: two"
// Prints "index: 2, value: three"

 

 

3. with 고차함수 (enumerated + filter + map)

let array = ["one", "two", "three"]
let newArray = array.enumerated()
                    .filter { $0.offset % 2 == 0 }
                    .map { $0.element }
print(newArray)
// Prints ["one", "three"]

 

 

 

📚 참고

https://developer.apple.com/documentation/swift/array/enumerated()