A function that takes a sequence of type

I need a function that takes a sequence Int. Here is what I want to write:

func process(items: Sequence<Int>) {
   items.forEach { ... }
}

Error: "It is not possible to specialize the non-standard type" Sequence ".

Fixed (I think):

func process<S: Sequence>(items: S) where S.Iterator.Element == Int {
    items.forEach { ... }
}

Pretty little more detailed.

I know that the Sequence protocol has an associated type Iteratorthat it has Element. But I'm not quite sure why I have to solve the requirement Intin such a strange way.

What are the basic concepts that make the first version inoperable, but the second? What does the error mean?

+4
source share
3 answers

. . ( " ", " " ) Swift. , Sequence, , . , Sequence - .

, , , . . , , , , , . , .

, , Sequence Iterator, IteratorProtocol, turn Element ( ).

+1

Int?

func process(items: [Int]) {
   items.forEach { ... }
}
0

You can use Variadic Parameters :

func process(items: Int...) {
    items.forEach { (item) in
        //do stuff with your 'item'
    }
}
0
source

Source: https://habr.com/ru/post/1655857/


All Articles