요소에 대한 순차적이고 반복적인 접근을 제공하는 프로토콜

 

시퀀스는 한 번에 하나씩 살펴볼 수 있는 값의 리스트입니다. 시퀀스의 element를 반복하는 가장 일반적인 방법은 for-in 루프를 사용하는 것입니다

let oneTwoThree = 1...3
for number in oneTwoThree {
    print(number)
}
// Prints "1"
// Prints "2"
// Prints "3"

 

이 기능은 간단해 보이지만, 이를 통해 모든 시퀀스에서 수행할 수 있는 많은 작업에 액세스할 수 있습니다. 예를 들어 특정 값을 포함하는지 여부를 확인하려면 각 값을 순차적으로 테스트하여 일치하는 항목을 찾거나 시퀀스의 끝에 도달할 때까지 진행할 수 있습니다. 다음 예제는 특정 곤충이 배열에 있는지 여부를 확인합니다.

let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
var hasMosquito = false
for bug in bugs {
    if bug == "Mosquito" {
        hasMosquito = true
        break
    }
}
print("'bugs' has a mosquito: \(hasMosquito)")
// Prints "'bugs' has a mosquito: false"

 

Sequence 프로토콜은 시퀀스의 값에 순차적으로 액세스하는 작업에 따라 많은 일반적인 작업에 대한 기본 구현을 제공합니다. 더 명확하고 간결한 코드를 위해 위의 예제는 모든 시퀀스가 Sequence에서 상속하는 배열의 contains(_:) 메서드를 수동으로 반복하는 대신 사용할 수 있습니다.

if bugs.contains("Mosquito") {
    print("Break out the bug spray.")
} else {
    print("Whew, no mosquitos!")
}
// Prints "Whew, no mosquitos!"

Conforming to the Sequence Protocol

자체 사용자 지정 유형을 Sequence에 준수하도록 만들면 for-in looping 및 contains 메서드와 같은 여러 유용한 작업을 간단하게 수행할 수 있습니다. 사용자 지정 유형에 Sequence 준수를 추가하려면 interator를 반환하는 makeIterator() 메서드를 추가하면 됩니다. makeIterator() 메서드는 Sequence 프로토콜 내부에 존재하는 함수입니다.

public protocol Sequence {
   ...
   func makeIterator() -> Self.Iterator
}

 

만약 iterator 를 만드려면 IteratorProtocol 프로토콜의 요구 사항을 구현하고 Sequence 및 IteratorProtocol에 모두 준수해야합니다.

 

여기에는 타입이 Sequence, IteratorProtocol 모두 준수하기 때문에 자체 iterator 역할을 하는 Countdown 시퀀스에서 makeIterator() 메서드는 기본 구현으로 제공되기 때문에 따로 구현하지 않아도 됩니다.

struct Countdown: Sequence, IteratorProtocol {
    var count: Int


    mutating func next() -> Int? {
        if count == 0 {
            return nil
        } else {
            defer { count -= 1 }
            return count
        }
    }
}


let threeToGo = Countdown(count: 3)
for i in threeToGo {
    print(i)
}
// Prints "3"
// Prints "2"
// Prints "1"

var iterator = [1,2,3,4,5].makeIterator()
while let value = iterator.next() {
    print(value)
}
// Prints "1"
// Prints "2"
// Prints "3"
// Prints "4"
// Prints "5"

 

ytw_developer