Can closures to Standard Library protocol methods be stateful?

I was looking at making an efficiency override for MutableCollection.partition(by:) in a sample BitArray type. I could just segregate for all false go before all true, or vice versa, and have partition call that. But that’s only valid if the belongsInSecondPartition closure must be pure; if stateful closures are allowed then I won’t override and use the default routine to iterate over all elements.

What do you mean by stateful? The closure can be anything that’s syntactically valid Swift (which includes matching the type signature). Beyond that, you can make no assumptions.

Currently all closures are allowed to be stateful, even if many of them aren’t. There’s no way currently to require that any closure parameter is a pure function.

1 Like

That the comparison object maintains state so it could change its criteria later. An example could be a predicate that returns true for prime numbers until 20 are read, then it switches to composite numbers.

Everything that the function captures can be used as function state, so you just need to define the state outside of it.

func generateStatefulFunction() -> (() -> Void) {
    var state = 0
    return {
        defer { state += 1 }
        return state