ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Swift- enumerated()
    developing study 2024. 1. 11. 22:37

    이 메소드를 많이 썼던 경우는 뷰에서 리스트를 보여줄 때 for문에서 사용했었다.

    근데 정확히 공부하지 않고 썼었어서 이게 정확히 뭔지 모르다보니 활용할줄 몰라 이번에 다시 정리하게 됐다.

    사전적으로 enumerate는

    mention(a number of things)one by one

    한국어로는 열거하다라는 뜻이 있다.

    배열이 있다면 한 개씩 꺼내어 놓는다는 느낌?인걸까..

    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.
    func enumerated() -> EnumeratedSequence<Self>​

    애플 문서 설명을 보면 (n,x)를 리턴한다.

    n : 0부터 시작하는 연속된 정수를 나타내고

    x : 요소의 순서를 나타낸다고 한다.

     

    예시를 보면, Swift 문자의 character들을 enumerate하게 되면 각 문자와 순서를 알 수 있다.

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

     

     

    그런데, 아직 이해가 되지 않는 부분 : zip(_:_)을 사용해라라고 하는 부분.

    -> 정확한 인덱스라기보다 오프셋이라고 이해하는게 더 좋을 것 같다.

    When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value. These counters can be used as indices only in instances of zero-based, integer-indexed collections, such as Array and ContiguousArray. For other collections the counters may be out of range or of the wrong type to use as an index. To iterate over the elements of a collection with its indices, use the zip(_:_:) function.

     

    'developing study' 카테고리의 다른 글

    Swift - replacingOccurences/Subrange  (0) 2024.01.12
    Swift - CaseIterable  (1) 2024.01.12
    Swift - components이용해 문자열 쪼개기  (0) 2024.01.11
    Swift - compactmap  (0) 2024.01.08
    Swift - reduce  (0) 2024.01.04

    댓글

Designed by Tistory.