ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Swift] enumerated()
    Swift 2022. 2. 8. 01:58

    Instance Method

    enumerated()

    (n, x) 쌍의 μ‹œν€€μŠ€λ₯Ό λ°˜ν™˜ν•œλ‹€. μ—¬κΈ°μ„œ n은 0μ—μ„œ μ‹œμž‘ν•˜λŠ” 연속적인 μ •μˆ˜λ₯Ό λ‚˜νƒ€λ‚΄κ³ , xλŠ” μ‹œν€€μŠ€μ˜ μš”μ†Œλ₯Ό λ‚˜νƒ€λ‚Έλ‹€.


    Declaration

    func enumerated() -> EnumeratedSequence<Array<Element>>

    γ…€

    Return Value

    μ‹œν€€μŠ€λ₯Ό μ—΄κ±°ν•˜λŠ” 쌍의 μ‹œν€€μŠ€μ΄λ‹€.

    γ…€

    Discussion

    μ•„λž˜ μ˜ˆμ œλŠ” β€œSwift” λ¬Έμžμ—΄μ˜ 문자λ₯Ό μ—΄κ±°ν•˜κ³ , λ¬Έμžμ—΄μ—μ„œμ˜ 각 문자의 μœ„μΉ˜μ™€ 문자λ₯Ό ν•¨κ»˜ 좜λ ₯ν•œλ‹€.

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

    γ…€

    μ»¬λ ‰μ…˜μ„ μ—΄κ±°ν•  λ•Œ, 각 쌍의 μ •μˆ˜ 뢀뢄은 열거에 λŒ€ν•œ μΉ΄μš΄ν„°μ΄μ§€λ§Œ 쌍으둜 κ΅¬μ„±λœ κ°’μ˜ μΈλ±μŠ€κ°€ 될 ν•„μš”λŠ” μ—†λ‹€. μ΄λŸ¬ν•œ μΉ΄μš΄ν„°λŠ” λ°°μ—΄μ΄λ‚˜ ContinuousArray와 같은 0λΆ€ν„° μ‹œμž‘ν•˜λŠ” μ •μˆ˜ 인덱슀 μ»¬λ ‰μ…˜μ˜ μΈμŠ€ν„΄μŠ€μ—μ„œλ§Œ 인덱슀둜 μ‚¬μš©ν•  수 μžˆλ‹€. λ‹€λ₯Έ μ»¬λ ‰μ…˜μ˜ 경우, μΉ΄μš΄ν„°κ°€ λ²”μœ„λ₯Ό λ²—μ–΄λ‚˜κ±°λ‚˜ 인덱슀둜 μ‚¬μš©ν•˜κΈ°μ— 잘λͺ»λœ μœ ν˜•μΌ μˆ˜λ„ μžˆλ‹€. μΈλ±μŠ€μ™€ ν•¨κ»˜ μ»¬λ ‰μ…˜μ˜ μš”μ†Œλ₯Ό λ°˜λ³΅ν•˜λ €λ©΄, zip(_:_:) ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜λ©΄ λœλ‹€.

    γ…€

    μ•„λž˜ μ˜ˆμ œλŠ” μ§‘ν•©μ˜ 색인 및 μš”μ†Œμ— λŒ€ν•΄ λ°˜λ³΅ν•˜λ©°, 5자 μ΄ν•˜μ˜ μ΄λ¦„μ˜ μƒ‰μΈλ“€λ‘œ κ΅¬μ„±λœ λͺ©λ‘μ„ μž‘μ„±ν•œλ‹€.

    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)
        }
    }

    γ…€

    이제 shortIndices 배열이 names μ§‘ν•©μ—μ„œ 문자 μˆ˜κ°€ 5개 μ΄ν•˜μΈ μš”μ†Œλ“€μ˜ 인덱슀λ₯Ό λ³΄μœ ν•˜λ―€λ‘œ, ν•΄λ‹Ή 인덱슀λ₯Ό μ‚¬μš©ν•˜μ—¬ μ§‘ν•©μ˜ μš”μ†Œμ— μ ‘κ·Όν•  수 μžˆλ‹€.

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

    γ…€
    μ‹œκ°„ λ³΅μž‘λ„: O(1)

    λŒ“κΈ€

Designed by Tistory.