Swift

[Swift] 배열에서 index 사용 | enumerated, indices

하이D:) 2023. 9. 17. 13:52

Swift를 처음 접했을 때, 자바스크립트처럼 배열을 forEach 혹은 for 문과 같은 반복문에 돌릴 때 인덱스값을 사용하고 싶었다. 그때 구글링해서 찾았던 방법이 enumerated() 메서드를 사용하여 리턴된 배열로 for문을 돌려서 튜플 형태의 요소를 뽑아서 .offset 값을 사용하는 것이었다. 

지금 생각해보면 그 때 enumerated() 메서드로 반환되는 게 정확히 뭔지 튜플을 (index, element)과 같이 어떻게 분해해서 사용하는지 제대로 이해하지 못하고 그냥 사용했던 것 같아서 다시 한번 정리해 본다.

 

# 🥨 enumerated()

일단 enumerated에 대한 공식문서에서의 정의는 아래와 같다.

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence. 즉, (n,x) 쌍으로 된 시퀀스를 반환하며 여기서 n은 0에서 시작하는 연속 정수를 나타내고 x는 시퀀스의 요소를 나타내는 것이다.

 

배열에 enumerated 메서드를 실행하면 배열 각 요소가 (offset: , element: ) 네임드 튜플 형태가 되어 저장된다. EnumeratedSequence<Self> 형태를 리턴하며 리턴한 시퀀스의 각 요소를 확인해보고 싶으면 for문이나 forEach문을 돌려보면된다.

let strArray = ["a", "b", "c", "d", "e"]

//for문
for el in strArray.enumerated() {
    print("el", el)
    print("el.offset", el.offset)
    print("el.element", el.element)
}

//forEach
strArray.enumerated().forEach{ el in
    print("el.offset", el.offset)
    print("el.element", el.element)
}

 

그리고 튜플 형태를 분해해서 바인딩시켜 사용하고 싶다면 아래와 같은 방법을 사용할 수도 있다.

//튜플 분해를 한다면
for (index, item) in strArray.enumerated() {
    print("index", index)
    print("item", item)
}

strArray.enumerated().forEach{ index, item in
    print("index", index)
    print("item", item)
}

//클로저에서 아규먼트 이름 축약 $0, $1
strArray.enumerated().forEach{
    print("$0", $0)
    print("$1", $1)
}

 

# 🥨 indices

indices는 컬렉션 데이터 타입에서 사용되는 중요한 속성이다. 컬렉션 내의 각 원소의 위치를 나타내주며 배열 (Array), 문자열(String), 세트(Set) 및 다른 컬렉션 유형에서 indices를 사용하여 해당 컬렉션의 인덱스 집합을 얻을 수 있다.

 

indices를 사용하면 배열의 인덱스 범위를 추출하거나 반복문에서 사용할 때 인덱스를 처리하는 것이 훨씬 간단해진다.

let array = [1, 2, 3, 4, 5]
let arrayIndices = array.indices

print(arrayIndices) //0..<5
print(type(of : arrayIndices)) //Range<Int>

 

for과 forEach를 활용한 예시이며 strArray.indices는 배열 strArray의 모든 유효한 인덱스를 나타내는 범위(Range)를 반환한다. 그런 다음 반복문을 사용하여 각 인덱스를 가져와서 해당위치의 요소를 출력할 수 있는 것이다.

let strArray = ["a", "b", "c", "d", "e"]
print(strArray.indices) //0..<5

for index in strArray.indices {
    print("index", index)
    print("item", strArray[index])
}

strArray.indices.forEach { index in
    print("index", index)
    print("item", strArray[index])
}

 

# 🥨  직접 반복 횟수(범위) 지정

아래와 같이 직접 반복 횟수(범위)지정해서 index값을 활용해 줄 수 있는 방법도 있다.

let strArray = ["a", "b", "c", "d", "e"]

for index in 0..<strArray.count {
    print("(index: \(index) item: \(strArray[index]))")
}