dev._.note

[Swift] enumerated() 배열의 인덱스 가져오기 본문

Dev/SWIFT

[Swift] enumerated() 배열의 인덱스 가져오기

Laena 2023. 10. 26. 17:32

👏 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.

 

array값에 enumerated()함수를 사용하면, (index, value) 튜플형식으로 구현된 리스트형이 리턴

 


(n, x)로 이루어진 쌍을 리턴한. (튜플 형태로 리턴)
여기서 n은 0부터 x까지의 연속적 숫자를 뜻하고 x는 해당 순서의 요소.

 

아래는 공식문서의 enumerated() 함수 사용법입니다.

func enumerated() -> EnumeratedSequence<Self>
for (n, c) in "Swift".enumerated() {
    print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"

 

직접 사용해본 예시

let arr = ["one", "two", "three"]
print(arr.enumerated()) // EnumeratedSequence<Array<String>>(_base: ["one", "two", "three"])
    for (index, number) in arr.enumerated() {
        print("\(index), \(number)")
}

// 0, one
// 1, two
// 2, three

 

Apple 공식문서

https://developer.apple.com/documentation/swift/int/words-swift.struct/enumerated()

 

enumerated() | Apple Developer Documentation

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

developer.apple.com

 

'Dev > SWIFT' 카테고리의 다른 글

[Swift] prefix 와 suffix  (0) 2023.10.27
[Swift] init(repeating:count:)  (0) 2023.10.27
[Swift] zip 함수  (0) 2023.10.26
[Swift] reverse() 와 reversed()의 차이점  (1) 2023.10.25
[Swift] Int형 정수  (0) 2023.10.25