programing

Swift에서 인덱스와 요소를 사용하여 루프를 반복하는 방법

lovejava 2023. 4. 24. 21:04

Swift에서 인덱스와 요소를 사용하여 루프를 반복하는 방법

Python과 수?enumerate

for index, element in enumerate(list):
    ...

예. Swift 3.0부터는 각 요소의 인덱스와 해당 값이 필요한 경우 이 메서드를 사용하여 어레이를 반복할 수 있습니다.인덱스와 배열의 각 항목 값으로 구성된 쌍의 시퀀스를 반환합니다.예를 들어 다음과 같습니다.

for (index, element) in list.enumerated() {
  print("Item \(index): \(element)")
}

3.0 2. 3.0으로 .enumerate():

for (index, element) in list.enumerate() {
    print("Item \(index): \(element)")
}

2.0, Swift 2.0 버전enumerate글로벌 함수였습니다.

for (index, element) in enumerate(list) {
    println("Item \(index): \(element)")
}

Swift 5는 다음과 같은 메서드를 제공합니다.Arrayenumerated()에는 다음 선언이 있습니다.

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

쌍의 시퀀스(n, x)를 반환합니다.여기서 n은 0에서 시작하는 연속 정수를 나타내고 x는 시퀀스의 요소를 나타냅니다.


가장 간단한 경우에는 다음을 사용할 수 있습니다.enumerated()을 위해예를 들어 다음과 같습니다.

let list = ["Car", "Bike", "Plane", "Boat"]
for (index, element) in list.enumerated() {
    print(index, ":", element)
}

/*
prints:
0 : Car
1 : Bike
2 : Plane
3 : Boat
*/

'있다', '어울리다', '어울리다'만 하는 것은 .enumerated()을 위해이라면, in약 in in in in in in in inenumerated()다음과 같은 코드에 대한 for 루프가 있는 경우는, 잘못하고 있습니다.

let list = [Int](1...5)
var arrayOfTuples = [(Int, Int)]()

for (index, element) in list.enumerated() {
    arrayOfTuples += [(index, element)]
}

print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

이를 위한 보다 빠른 방법은 다음과 같습니다.

let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]

대신 신, 음, 음, 음, 다, 다, 다, 다, 다, 다를 수 있다.enumerated()map:

let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]

그리고 한계가 있긴 하지만forEach는 for loop 를 할 수 .

let list = [Int](1...5)
list.reversed().enumerated().forEach { print($0, ":", $1) }

/*
prints:
0 : 5
1 : 4
2 : 3
3 : 2
4 : 1
*/

「」를 사용해 .enumerated() ★★★★★★★★★★★★★★★★★」makeIterator()할 수 있습니다.Array §:

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(type: .system)
        button.setTitle("Tap", for: .normal)
        button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        button.addTarget(self, action: #selector(iterate(_:)), for: .touchUpInside)
        view.addSubview(button)
    }

    @objc func iterate(_ sender: UIButton) {
        let tuple = generator.next()
        print(String(describing: tuple))
    }

}

PlaygroundPage.current.liveView = ViewController()

/*
 Optional((offset: 0, element: "Car"))
 Optional((offset: 1, element: "Bike"))
 Optional((offset: 2, element: "Plane"))
 Optional((offset: 3, element: "Boat"))
 nil
 nil
 nil
 */

Swift 2부터는 다음과 같이 컬렉션에서 열거 함수를 호출해야 합니다.

for (index, element) in list.enumerate() {
    print("Item \(index): \(element)")
}

사전에서 그렇게 하는 방법을 찾다가 이 답을 찾았는데, 쉽게 적응할 수 있더군요. 요소를 위해 튜플을 건네주면 됩니다.

// Swift 2

var list = ["a": 1, "b": 2]

for (index, (letter, value)) in list.enumerate() {
    print("Item \(index): \(letter) \(value)")
}

Swift 5.x:

목록 = [0, 1, 2, 3, 4, 5]

list.enumerated().forEach { (index, value) in
    print("index: \(index), value: \(value)")
}

아니면...

list.enumerated().forEach { 
    print("index: \($0.offset), value: \($0.element)")
} 

아니면...

for (index, value) in list.enumerated() {
    print("index: \(index), value: \(value)")
}

Swift 5.x:

는 개인적으로 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★forEach★★★★

list.enumerated().forEach { (index, element) in
    ...
}

쇼트 버전도 사용할 수 있습니다.

list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }

완전한 구성을 위해 배열 인덱스를 반복하고 첨자를 사용하여 해당 인덱스의 요소에 액세스할 수 있습니다.

let list = [100,200,300,400,500]
for index in list.indices {
    print("Element at:", index, " Value:", list[index])
}

각각에 사용

list.indices.forEach {
    print("Element at:", $0, " Value:", list[$0])
}

사용방법enumerated()방법.Tuples 컬렉션이 반환되는 것에 주의해 주세요.offsetelement:

for item in list.enumerated() {
    print("Element at:", item.offset, " Value:", item.element)
}

각각에 사용:

list.enumerated().forEach {
    print("Element at:", $0.offset, " Value:", $0.element)
}

그것들은 인쇄될 것이다.

요소: 0 값: 100

요소: 1 값: 200

요소: 2 값: 300

요소: 3 값: 400

요소: 4 값: 500

배열 인덱스(오프셋이 아님)와 해당 요소가 필요한 경우 컬렉션을 확장하고 고유한 메서드를 생성하여 인덱스 요소를 가져올 수 있습니다.

extension Collection {
    func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
        var index = startIndex
        for element in self {
            try body((index,element))
            formIndex(after: &index)
        }
    }
}

Alex가 제안하는 또 다른 구현 방법은 수집 인덱스의 요소를 압축하는 것입니다.

extension Collection {
    func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
        for element in zip(indices, self) { try body(element) }
    }
    var indexedElements: Zip2Sequence<Indices, Self> { zip(indices, self) }
}

테스트:

let list =  ["100","200","300","400","500"]

// You can iterate the index and its elements using a closure
list.dropFirst(2).indexedElements {
    print("Index:", $0.index, "Element:", $0.element)
}

// or using a for loop
for (index, element) in list.indexedElements  {
    print("Index:", index, "Element:", element)
}

이것으로 끝이다

인덱스: 2 요소: 300

색인: 3 요소: 400

인덱스: 4 요소: 500

인덱스: 0 요소: 100

인덱스: 1 요소: 200

인덱스: 2 요소: 300

색인: 3 요소: 400

인덱스: 4 요소: 500

열거 루프를 사용하면 원하는 결과를 얻을 수 있습니다.

스위프트 2:

for (index, element) in elements.enumerate() {
    print("\(index): \(element)")
}

Swift 3 & 4:

for (index, element) in elements.enumerated() {
    print("\(index): \(element)")
}

또는 for 루프를 통해 동일한 결과를 얻을 수도 있습니다.

for index in 0..<elements.count {
    let element = elements[index]
    print("\(index): \(element)")
}

도움이 됐으면 좋겠다.

기본 열거

for (index, element) in arrayOfValues.enumerate() {
// do something useful
}

아니면 스위프트3로...

for (index, element) in arrayOfValues.enumerated() {
// do something useful
}

열거, 필터링 및 지도

단, 저는 Enumerate를 맵이나 필터와 조합하여 사용하는 경우가 가장 많습니다.예를 들면, 몇개의 어레이로 운용하는 경우입니다.

이 배열에서는 홀수 또는 짝수 인덱스 요소를 필터링하여 Ints에서 Doubles로 변환하려고 했습니다. ★★★★★★★★★★★★★★★★★.enumerate()인덱스와 요소를 가져온 다음 필터를 통해 인덱스를 확인하고 마지막으로 결과 태플을 제거하기 위해 요소에만 매핑합니다.

let evens = arrayOfValues.enumerate().filter({
                            (index: Int, element: Int) -> Bool in
                            return index % 2 == 0
                        }).map({ (_: Int, element: Int) -> Double in
                            return Double(element)
                        })
let odds = arrayOfValues.enumerate().filter({
                            (index: Int, element: Int) -> Bool in
                            return index % 2 != 0
                        }).map({ (_: Int, element: Int) -> Double in
                            return Double(element)
                        })

「」를 사용합니다..enumerate()는 동작하지만 요소의 진정한 인덱스는 제공하지 않습니다.이는 0으로 시작하여 연속되는 각 요소에 대해 1씩 증가하는 Int만 제공합니다.은 보통가 없지만, 이 동작과 함께 치 않은 이 발생할 수 .ArraySlice합니다.type 다음 코드를 사용합니다.

let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5

let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4

var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
    test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds

이것은 다소 교묘한 예이며, 실제로 일반적인 문제는 아니지만, 저는 이것이 일어날 수 있다는 것을 알 가치가 있다고 생각합니다.

Swift 3부터는

for (index, element) in list.enumerated() {
  print("Item \(index): \(element)")
}

열거 루프의 공식은 다음과 같습니다.

for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}

자세한 내용은 여기를 참조하십시오.

「 」를 사용하고 에게는, 「 」를 해 주세요.forEach.

스위프트 4

extension Array {
  func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
    try zip((startIndex ..< endIndex), self).forEach(body)
  }
}

또는

array.enumerated().forEach { ... }

8및 3:는 Xcode 8 swift Swift 3 : 음음음음음음음음음음 x x x x x x x x x x x x x x x x x x x x x를 사용하여 할 수 .tempArray.enumerated()

예:

var someStrs = [String]()

someStrs.append("Apple")  
someStrs.append("Amazon")  
someStrs += ["Google"]    


for (index, item) in someStrs.enumerated()  
{  
        print("Value at index = \(index) is \(item)").  
}

콘솔:

Value at index = 0 is Apple
Value at index = 1 is Amazon
Value at index = 2 is Google

에는, 「마음껏」를 해 주세요.enumerated()어레이상의 메서드:

for (index, element) in list.enumerated() {
    print("\(index) - \(element)")
}

기능 프로그래밍에서는 다음과 같이 .enumerated()를 사용합니다.

list.enumerated().forEach { print($0.offset, $0.element) } 

iOS 8.0 / Swift 4.0 이상

하시면 됩니다.forEachApple 문서에 따르면:

쌍의 시퀀스(n, x)를 반환합니다.여기서 n은 0에서 시작하는 연속 정수를 나타내고 x는 시퀀스의 요소를 나타냅니다.

let numberWords = ["one", "two", "three"]

numberWords.enumerated().forEach { (key, value) in
   print("Key: \(key) - Value: \(value)")
}

로든 좀 더 인 모습을 for인덱스를 사용하여 배열의 요소에 액세스하는 루프:

let xs = ["A", "B", "C", "D"]

for i in 0 ..< xs.count {
    print("\(i) - \(xs[i])")
}

출력:

0 - A
1 - B
2 - C
3 - D

이를 구현하기 위해 열거 함수를 호출했습니다.맘에 들다

    for (index, element) in array.enumerate() {
     index is indexposition of array
     element is element of array 
   }

언급URL : https://stackoverflow.com/questions/24028421/how-to-iterate-a-loop-with-index-and-element-in-swift