ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Swift Tips and Tricks - .enumerated()
    Swift/Tips & Tricks 2021. 10. 12. 13:21

    Swift 에서 for statement 내에 종종 .enumerated() 가 쓰일 때가 있어요. ( enumerate: 열거하다, 세다 ) 

     

    먼저, 예시부터 드릴게요 ! 

    let names = ["james", "kelvin", "katherine"]
    
    for (idx, name) in names.enumerated() {
        print("idx: \(idx), name: \(name)")
    }
    
    //idx: 0, name: james
    //idx: 1, name: kelvin
    //idx: 2, name: katherine

    주로 위 예시와 같이 index 와 함께 사용합니다. Syntax 는 위와 같이 (index, element) 로 써주시면 편해요! 

    이제, option + click 설명과 함께 알아보아요. 

     

     

    Summary

    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) 을 순서대로 return 합니다. ( n: 0부터 시작하는 연속된 정수 값 , x: element)

     

    Declaration

    func enumerated() -> EnumeratedSequence<Self>

     

    Discussion

    This example enumerates the characters of the string “Swift” and prints each character along with its place in the string.

    아래 예제는 "Swift"  characters 를 string 내에서의  charcter 와 그 위치를 함께 출력합니다.

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

    Collection 을 enumerate 할 때, 각 쌍의 정수 부분은 enumeration 의 counter 로써, 항상 순서쌍의 index 인 것은 아니에요. Counters 는 zero-based, integer-indexed collections (연속된 배열,  Array) 의 instances 에서만 index 로 사용될 수 있습니다.다른 collections 에서 counters 는 range 밖 값일 수도 있고, index 로 사용하기 힘든 다른 type 의 값이 될 수도 있습니다. Collection 의 elements 에 대해 index 와 함께 iterate 를 원할 때에는, zip(_:_:) function 과 함께 사용하세요. 

     

    아래 예제에서는 Set Collection 에서 indices 와 elements 에 대해 iterate 하고, 5 자 이하의 names indices 로 shorterIndices 를 만들고 있습니다. 

    let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
    var shorterIndices: [Set<String>.Index] = []
    for (i, name) in zip(names.indices, names) {
        if name.count <= 5 {
            shorterIndices.append(i)
        }
    }

    Now that the shorterIndices array holds the indices of the shorter names in the names set, you can use those indices to access elements in the set.

    shorterIndices array 는 names set 중 짧은 names 의 indices 를 가지고 있습니다. names 에 shorterIndices 를 이용하여 짧은 names 의 값들을 구할 수 있습니다. 

    for i in shorterIndices {
        print(names[i])
    }
    // Prints "Sofia"
    // Prints "Mateo"

    Complexity

    O(1)

     

    Returns

    A sequence of pairs enumerating the sequence.

     

     

    지금까지 enumerated() 가 순서쌍에 대해 index 와 짝지어 활용하는 것이라고 막연하게 알고있었는데 zip 이라는 method 도 함께 알게되었네요! 

     

    이상 enumerated() 포스팅을 마치겠습니다. 

Designed by Tistory.