Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generator in Swift?

Can I create a generator in Swift?

With iterator, I need store intermediate results, for example:

struct Countdown: IteratorProtocol, Sequence {

    private var value = 0

    init(start: Int) {
        self.value = start
    }

    mutating func next() -> Int? {
        let nextNumber = value - 1
        if nextNumber < 0 {
            return nil
        }

        value -= 1

        return nextNumber
    }
}

for i in Countdown(start: 3) {
    print(i)
} // print 1 2 3

In this example, I need store the value.

In my situation, I want to use generator instead of iterator, because I don't want store the intermediate results of my sequence in each next.

like image 556
macabeus Avatar asked May 30 '17 03:05

macabeus


People also ask

How to generate random in Swift?

To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.


3 Answers

Understanding how generators work (and why they are less important in swift) is at first difficult coming from Python.

Up to Swift v2.1 there was a protocol called GeneratorType. This was renamed to IteratorProtocol in Swift v3.0+. You can conform to this protocol to make your own objects that do just-in-time computations similar to what can be done in Python.

More information can be found in the Apple Documentation: IteratorProtocol

A simple example from IteratorProtocol page:

struct CountdownIterator: IteratorProtocol {
    let countdown: Countdown
    var times = 0

    init(_ countdown: Countdown) {
        self.countdown = countdown
    }

    mutating func next() -> Int? {
        let nextNumber = countdown.start - times
        guard nextNumber > 0
            else { return nil }

        times += 1
        return nextNumber
    }
}

let threeTwoOne = Countdown(start: 3)
for count in threeTwoOne {
    print("\(count)...")
}
// Prints "3..."
// Prints "2..."
// Prints "1..."

However, you need to think about why you are using a generator:

Swift automatically does something "called copy on write." This means that many of the cases that use a Python generator to avoid the large copying cost of collections of objects (arrays, lists, dictionaries, etc) are unnecessary in Swift. You get this for free by using one of the types that use copy on write.

Which value types in Swift supports copy-on-write?

It is also possible to use a wrapper to force almost any object to be copy on write, even if it is not part of a collection:

How can I make a container with copy-on-write semantics?

The optimizations in swift usually mean that you do not not have to write generators. If you really do need to (usually because of data heavy, scientific calculations) it is possible as above.

like image 166
WaterNotWords Avatar answered Nov 15 '22 01:11

WaterNotWords


Based on the code you provided and the little bit knowledge of generators that I do have, you can do something like

struct Countdown {
    private var _start = 0
    private var _value = 0

    init(value: Int) {
        _value = value
    }

    mutating func getNext() -> Int? {
        let current = _start
        _start += 1
        if current <= _value {
            return current
        } else {
            return nil
        }
    }
}

and then wherever you want to use it, you can do something like

var counter = Countdown(value: 5)
while let value = counter.getNext() {
    print(value)
}
like image 20
Malik Avatar answered Nov 15 '22 02:11

Malik


Walter provides a lot of good information, and generally you shouldn't be doing this in Swift, but even if you wanted an Iterator, the right way to do it is with composition, not by building your own. Swift has a lot of existing sequences that can be composed to create what you want without maintaining your own state. So in your example, you'd differ to a range's iterator:

struct Countdown: Sequence {

    private var value = 0

    init(start: Int) {
        self.value = start
    }

    func makeIterator() -> AnyIterator<Int> {
        return AnyIterator((0..<value).reversed().makeIterator())
    }
}

for i in Countdown(start: 3) {
    print(i)
} // print 1 2 3

Something has to keep the state; that's the nature of these kinds of functions (even in a world with coroutines). It's fine not to maintain it directly; just delegate to a more primitive type. Swift has a couple of dozen built-in Iterators you can use to build most things you likely need, and any iterator can be lifted to an AnyIterator to hide the implementation details. If you have something custom enough that it really requires a next(), then yes, storing the state is your problem. Something has to do it. But I've found this all to be extremely rare, and often suggests over-design when it comes up.

like image 35
Rob Napier Avatar answered Nov 15 '22 01:11

Rob Napier