sourcetip

루프를 역순으로 빠르게 반복하려면 어떻게 해야 합니까?

fileupload 2023. 4. 13. 21:06
반응형

루프를 역순으로 빠르게 반복하려면 어떻게 해야 합니까?

Playground에서 for 루프를 사용하면 for 루프의 첫 번째 파라미터를 가장 높은 값으로 변경할 때까지 모든 것이 정상적으로 동작했습니다.(내림차순으로 반복)

이거 버그예요?다른 사람은 가지고 있었나요?

for index in 510..509
{
    var a = 10
}

사형 집행 횟수를 표시하는 카운터가 계속 똑딱거립니다...

여기에 이미지 설명 입력

6 는 Xcode 6 6 4 음 4 음 음 음 음 음 4 음 음 음 음 음 음 x x x x x x の x with2개의 하였습니다.stride(from: to: by:) , , , , , , , , , , 전용 범위와 함께 합니다.stride(from: through: by:)포함 범위와 함께 사용됩니다.

범위를 역순으로 반복하려면 다음과 같이 사용할 수 있습니다.

for index in stride(from: 5, to: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2

for index in stride(from: 5, through: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2, 1

도 「」, 「」는 것에 해 주세요.Range that that that that that that that that that that that that that that that that that that that that that that that that that that that that that를 반환하는 입니다.StrideTo ★★★StrideThrough, , 와는 다르게 정의됩니다.Range★★★★★★★★★★★★★★★★★★.

에서는 " " " 가 사용되었습니다.by()「」의 Range4번입니다.어떻게 동작했는지 확인하려면 편집 내역을 확인하십시오.

역함수를 범위에 적용하여 역방향으로 반복합니다.

Swift 1.2 이전의 경우:

// Print 10 through 1
for i in reverse(1...10) {
    println(i)
}

하프 오픈 범위에서도 동작합니다.

// Print 9 through 1
for i in reverse(1..<10) {
    println(i)
}

★★★★★★reverse(1...10)는 타입의 합니다.[Int] 이 작을 경우 가 없을 수 , 이 경우 '어느 정도'를 사용하는 lazy 그림과 또는 것을 합니다.stride범위가 큰 경우 응답하십시오.


배열을 , 「」를 해 주세요.lazy reverse() 개의 Playground를 배열을 Ints!

테스트:

var count = 0
for i in lazy(1...1_000_000_000_000).reverse() {
    if ++count > 5 {
        break
    }
    println(i)
}

Xcode 7의 Swift 2.0의 경우:

for i in (1...10).reverse() {
    print(i)
}

2. Swift 2.(1...1_000_000_000_000).reverse()은 「」입니다.ReverseRandomAccessCollection<(Range<Int>)>잘 거죠.

var count = 0
for i in (1...1_000_000_000_000).reverse() {
    count += 1
    if count > 5 {
        break
    }
    print(i)
}

Swift 3.0의 경우 reverse().reversed():

for i in (1...10).reversed() {
    print(i) // prints 10 through 1
}

Swift 3용으로 업데이트됨

다음 답변은 사용 가능한 옵션의 요약입니다.당신의 요구에 가장 적합한 것을 고르세요.

reversed: 내 " " "

앞으로

for index in 0..<5 {
    print(index)
}

// 0
// 1
// 2
// 3
// 4

뒤로

for index in (0..<5).reversed() {
    print(index)
}

// 4
// 3
// 2
// 1
// 0

reversed : 소소 。SequenceType

let animals = ["horse", "cow", "camel", "sheep", "goat"]

앞으로

for animal in animals {
    print(animal)
}

// horse
// cow
// camel
// sheep
// goat

뒤로

for animal in animals.reversed() {
    print(animal)
}

// goat
// sheep
// camel
// cow
// horse

reversed: : " " " "

컬렉션을 반복할 때 인덱스가 필요할 수 있습니다. 경우에는 '어울리지 않다'를 사용하면 .enumerate()이것은 태플을 반환합니다.태플의 첫 번째 요소는 인덱스이고 두 번째 요소는 객체입니다.

let animals = ["horse", "cow", "camel", "sheep", "goat"]

앞으로

for (index, animal) in animals.enumerated() {
    print("\(index), \(animal)")
}

// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat

뒤로

for (index, animal) in animals.enumerated().reversed()  {
    print("\(index), \(animal)")
}

// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse

Ben Lachman이 답변에서 언급한 바와 같이, 당신은 아마도 다음과 같이 하기를 원할 것입니다..enumerated().reversed().reversed().enumerated()(어느 쪽인가 하면)

스트라이드: 숫자

스트라이드는 범위를 사용하지 않고 반복하는 방법입니다.두 가지 형태가 있습니다.코드 끝에 있는 코멘트에는 범위 버전이 표시됩니다(증분 사이즈가 1이라고 가정).

startIndex.stride(to: endIndex, by: incrementSize)      // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex

앞으로

for index in stride(from: 0, to: 5, by: 1) {
    print(index)
}

// 0
// 1
// 2
// 3
// 4

뒤로

증가 크기 변경-1를 사용하면 과거로 돌아갈 수 있습니다.

for index in stride(from: 4, through: 0, by: -1) {
    print(index)
}

// 4
// 3
// 2
// 1
// 0

주의:to그리고.through차이.

스트라이드: SequenceType 요소

2개씩 포워딩

let animals = ["horse", "cow", "camel", "sheep", "goat"]

사용하고 있다2이 예에서는 다른 가능성을 보여 줍니다.

for index in stride(from: 0, to: 5, by: 2) {
    print("\(index), \(animals[index])")
}

// 0, horse
// 2, camel
// 4, goat

뒤로

for index in stride(from: 4, through: 0, by: -1) {
    print("\(index), \(animals[index])")
}

// 4, goat
// 3, sheep 
// 2, camel
// 1, cow  
// 0, horse 

메모들

스위프트 4 이후

for i in stride(from: 5, to: 0, by: -1) {
    print(i)
}
//prints 5, 4, 3, 2, 1

for i in stride(from: 5, through: 0, by: -1) {
    print(i)
}
//prints 5, 4, 3, 2, 1, 0

Swift 5에서는, 고객의 요구에 따라서, 다음의 4개의 Playground 코드의 예 중 하나를 선택해 문제를 해결할 수 있습니다.


#1. 사용방법ClosedRange reversed()방법

ClosedRange에는 라고 하는 메서드가 있습니다.reversed()method 선언은 다음과 같습니다.

func reversed() -> ReversedCollection<ClosedRange<Bound>>

집합의 요소를 역순으로 표시하는 뷰를 반환합니다.

사용방법:

let reversedCollection = (0 ... 5).reversed()

for index in reversedCollection {
    print(index)
}

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

다른 방법으로는Range reversed() 방법:

let reversedCollection = (0 ..< 6).reversed()

for index in reversedCollection {
    print(index)
}

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

#2. 사용방법sequence(first:next:)기능.

Swift Standard Library는 라고 하는 기능을 제공합니다.sequence(first:next:)에는 다음 선언이 있습니다.

func sequence<T>(first: T, next: @escaping (T) -> T?) -> UnfoldFirstSequence<T>

에서 생성된 시퀀스를 반환합니다.first의 반복적인 게으른 응용 프로그램next.

사용방법:

let unfoldSequence = sequence(first: 5, next: {
    $0 > 0 ? $0 - 1 : nil
})

for index in unfoldSequence {
    print(index)
}

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

#3. 사용방법stride(from:through:by:)기능.

Swift Standard Library는 라고 하는 기능을 제공합니다.stride(from:through:by:)에는 다음 선언이 있습니다.

func stride<T>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T> where T : Strideable

시작 값에서 종료 값(경우에 따라 포함)으로 지정된 양만큼 스테핑되는 시퀀스를 반환합니다.

사용방법:

let sequence = stride(from: 5, through: 0, by: -1)

for index in sequence {
    print(index)
}

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

대신 다음 명령을 사용할 수 있습니다.

let sequence = stride(from: 5, to: -1, by: -1)

for index in sequence {
    print(index)
}

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

#4로. 사용방법AnyIterator init(_:)

AnyIterator에는 라고 하는 이니셜라이저가 있습니다.init(_:)에는 다음 선언이 있습니다.

init(_ body: @escaping () -> AnyIterator<Element>.Element?)

을 그 를 만듭니다.next()★★★★★★ 。

사용방법:

var index = 5

guard index >= 0 else { fatalError("index must be positive or equal to zero") }

let iterator = AnyIterator({ () -> Int? in
    defer { index = index - 1 }
    return index >= 0 ? index : nil
})

for index in iterator {
    print(index)
}

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

따라 이전 수 . 코드에서는 확장 하여 리팩터링할 수 있습니다.Int복기를::::::

extension Int {

    func iterateDownTo(_ endIndex: Int) -> AnyIterator<Int> {
        var index = self
        guard index >= endIndex else { fatalError("self must be greater than or equal to endIndex") }

        let iterator = AnyIterator { () -> Int? in
            defer { index = index - 1 }
            return index >= endIndex ? index : nil
        }
        return iterator
    }

}

let iterator = 5.iterateDownTo(0)

for index in iterator {
    print(index)
}

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

Swift 2.0 이상의 경우 범위 컬렉션에 역방향으로 적용해야 합니다.

for i in (0 ..< 10).reverse() {
  // process
}

Swift 3.0에서는 .reversed()로 이름이 변경되었습니다.

Swift 4 이후

    let count = 50//For example
    for i in (1...count).reversed() {
        print(i)
    }

Swift 4.0

for i in stride(from: 5, to: 0, by: -1) {
    print(i) // 5,4,3,2,1
}

「 」를 to 추가:

for i in stride(from: 5, through: 0, by: -1) {
    print(i) // 5,4,3,2,1,0
}

어레이를 반복하고 싶은 경우(Array으로는 어떤 것이든SequenceType를 역방향으로 합니다을 사용하다몇 가지 추가 옵션이 있습니다.

, 「 」를 사용할 수 있습니다.reverse()어레이와 루프를 정상적으로 통과시킵니다., 저는 ,, 우를 사용하는 합니다.enumerate()오브젝트 및 인덱스를 포함하는 태플을 출력하기 때문에 대부분의 시간을 사용할 수 있습니다.

여기서 주의할 점은 올바른 순서로 호출하는 것이 중요하다는 것입니다.

for (index, element) in array.enumerate().reverse()

인덱스를 내림차순으로 생성합니다(일반적으로 예상하는 대로).반면:

for (index, element) in array.reverse().enumerate()NSArray)에입니다).reverseEnumerator)

는 배열을 뒤로 이동하지만 오름차순 인덱스를 출력합니다.

Swift 2.2, Xcode 7.3(10, 2016년 6월):

for (index,number) in (0...10).enumerate() {
    print("index \(index) , number \(number)")
}

for (index,number) in (0...10).reverse().enumerate() {
    print("index \(index) , number \(number)")
}

출력:

index 0 , number 0
index 1 , number 1
index 2 , number 2
index 3 , number 3
index 4 , number 4
index 5 , number 5
index 6 , number 6
index 7 , number 7
index 8 , number 8
index 9 , number 9
index 10 , number 10


index 0 , number 10
index 1 , number 9
index 2 , number 8
index 3 , number 7
index 4 , number 6
index 5 , number 5
index 6 , number 4
index 7 , number 3
index 8 , number 2
index 9 , number 1
index 10 , number 0

C-Style의 해 볼 수 .while대신 루프합니다. 3Swift 3에서 잘합니다.

var i = 5 
while i > 0 { 
    print(i)
    i -= 1
}

이렇게 하면 역순으로 1씩 감소합니다.

let num1 = [1,2,3,4,5]
for item in nums1.enumerated().reversed() { 

    print(item.offset) // Print the index number: 4,3,2,1,0
    print(item.element) // Print the value :5,4,3,2,1

}

또는 이 색인, 값 속성을 사용할 수 있습니다.

let num1 = [1,2,3,4,5]
for (index,item) in nums1.enumerated().reversed() { 

    print(index) // Print the index number: 4,3,2,1,0
    print(item) // Print the value :5,4,3,2,1

}
var sum1 = 0
for i in 0...100{
    sum1 += i
}
print (sum1)

for i in (10...100).reverse(){
    sum1 /= i
}
print(sum1)

reverse() 메서드를 사용하면 값을 쉽게 되돌릴 수 있습니다.

var i:Int
for i in 1..10.reversed() {
    print(i)
}

reverse() 메서드는 값을 반전시킵니다.

어레이의 리버스(reverse)는, 1개의 스텝으로 실행할 수 있습니다.

var arrOfnum = [1,2,3,4,5,6]
arrOfnum.reverse()

나한텐 이게 제일 좋은 방법이에요.

var arrayOfNums = [1,4,5,68,9,10]

for i in 0..<arrayOfNums.count {
    print(arrayOfNums[arrayOfNums.count - i - 1])
}

언급URL : https://stackoverflow.com/questions/24508592/how-to-iterate-for-loop-in-reverse-order-in-swift

반응형