Process Array in parallel using GCD - swift

I have a large array that I would like to process by handing slices of it to a few asynchronous tasks. As a proof of concept, I have the written the following code:
class TestParallelArrayProcessing {
let array: [Int]
var summary: [Int]
init() {
array = Array<Int>(count: 500000, repeatedValue: 0)
for i in 0 ..< 500000 {
array[i] = Int(arc4random_uniform(10))
}
summary = Array<Int>(count: 10, repeatedValue: 0)
}
func calcSummary() {
let group = dispatch_group_create()
let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
for i in 0 ..< 10 {
dispatch_group_async(group, queue, {
let base = i * 50000
for x in base ..< base + 50000 {
self.summary[i] += self.array[x]
}
})
}
dispatch_group_notify(group, queue, {
println(self.summary)
})
}
}
After init(), array will be initialized with random integers between 0 and 9.
The calcSummary function dispatches 10 tasks that take disjoint chunks of 50000 items from array and add them up, using their respective slot in summary as an accummulator.
This program crashes at the self.summary[i] += self.array[x] line. The error is:
EXC_BAD_INSTRUCTION (code = EXC_I386_INVOP).
I can see, in the debugger, that it has managed to iterate a few times before crashing, and that the variables, at the time of the crash, have values within correct bounds.
I have read that EXC_I386_INVOP can happen when trying to access an object that has already been released. I wonder if this has anything to do with Swift making a copy of the array if it is modified, and, if so, how to avoid it.

This is a slightly different take on the approach in #Eduardo's answer, using the Array type's withUnsafeMutableBufferPointer<R>(body: (inout UnsafeMutableBufferPointer<T>) -> R) -> R method. That method's documentation states:
Call body(p), where p is a pointer to the Array's mutable contiguous storage. If no such storage exists, it is first created.
Often, the optimizer can eliminate bounds- and uniqueness-checks within an array algorithm, but when that fails, invoking the same algorithm on body's argument lets you trade safety for speed.
That second paragraph seems to be exactly what's happening here, so using this method might be more "idiomatic" in Swift, whatever that means:
func calcSummary() {
let group = dispatch_group_create()
let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
self.summary.withUnsafeMutableBufferPointer {
summaryMem -> Void in
for i in 0 ..< 10 {
dispatch_group_async(group, queue, {
let base = i * 50000
for x in base ..< base + 50000 {
summaryMem[i] += self.array[x]
}
})
}
}
dispatch_group_notify(group, queue, {
println(self.summary)
})
}

When you use the += operator, the LHS is an inout parameter -- I think you're getting race conditions when, as you mention in your update, Swift moves around the array for optimization. I was able to get it to work by summing the chunk in a local variable, then simply assigning to the right index in summary:
func calcSummary() {
let group = dispatch_group_create()
let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
for i in 0 ..< 10 {
dispatch_group_async(group, queue, {
let base = i * 50000
var sum = 0
for x in base ..< base + 50000 {
sum += self.array[x]
}
self.summary[i] = sum
})
}
dispatch_group_notify(group, queue, {
println(self.summary)
})
}

You can also use concurrentPerform(iterations: Int, execute work: (Int) -> Swift.Void) (since Swift 3).
It has a much simpler syntax and will wait for all threads to finalise before returning.:
DispatchQueue.concurrentPerform(iterations: iterations) { i in
performOperation(i)
}

I think Nate is right: there are race conditions with the summary variable. To fix it, I used summary's memory directly:
func calcSummary() {
let group = dispatch_group_create()
let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
let summaryMem = UnsafeMutableBufferPointer<Int>(start: &summary, count: 10)
for i in 0 ..< 10 {
dispatch_group_async(group, queue, {
let base = i * 50000
for x in base ..< base + 50000 {
summaryMem[i] += self.array[x]
}
})
}
dispatch_group_notify(group, queue, {
println(self.summary)
})
}
This works (so far).
EDIT
Mike S has a very good point, in his comment below. I have also found this blog post, which sheds some light on the problem.

Any solution that assigns the i'th element of the array concurrently risks race condition (Swift's array is not thread-safe). On the other hand, dispatching to the same queue (in this case main) before updating solves the problem but results in a slower performance overall. The only reason I see for taking either of these two approaches is if the array (summary) cannot wait for all concurrent operations to finish.
Otherwise, perform the concurrent operations on a local copy and assign it to summary upon completion. No race condition, no performance hit:
Swift 4
func calcSummary(of array: [Int]) -> [Int] {
var summary = Array<Int>.init(repeating: 0, count: array.count)
let iterations = 10 // number of parallel operations
DispatchQueue.concurrentPerform(iterations: iterations) { index in
let start = index * array.count / iterations
let end = (index + 1) * array.count / iterations
for i in start..<end {
// Do stuff to get the i'th element
summary[i] = Int.random(in: 0..<array.count)
}
}
return summary
}
I've answered a similar question here for simply initializing an array after computing on another array

Related

Why doesn't adding an index to a Realm Object speed up my count query?

I have the following code I'm using to try to test indexing with Realm. I have an object class with a single Int value that is indexed, also an identical class, but unindexed.
After inserting 1 million rows of each class, with evenly distributed values, I run some queries to see the time it takes with and without indexes.
The time is basically the same (sometimes unindexed will be slightly faster, sometimes indexed will be slightly faster -- but within about 5% or something).
the results I get are these:
realm init6 took: 79.721125 ms
1000000
baseCountIndexed took: 0.233 ms
1000000
baseCountUnindexed took: 0.075833 ms
500000
getCountIndexedObjsViaFilterString took: 18.982542 ms
500000
getCountIndexedObjsViaWhereClosure took: 16.156041 ms
500000
getCountUnindexedObjsViaFilterString took: 17.985084 ms
500000
getCountUnindexedObjsViaWhereClosure took: 16.031917 ms
I would expect the indexed version to be faster -- seems like it should be close to the base count time, since an index should result in O(Log N) time -- the indexed version should at least be faster than unindexed.
What am I doing wrong?
The code I'm using follows: (long so I could make it complete / runnable)
The code basically inserts 1 million indexed objects, and 1 million unindexed objects, then gets the count of both types -- which is very fast -- and then does 2 different kinds of where clauses, one using a .filter(String), and one using a .where closure, to select 1/2 the objects, then do a count.
It is my understanding that the results coming from realm are lazy, and so the count should be done without loading the objects into memory.
The times for all 4 queries (indexed with .filter and indexed with .where, and unindexed for .filter & .where) all take about the same amount of time.
Edit:
After the answer from jay below, I ran the same code, with results not massively dissimilar -- I got about 33% speed increase by indexing, rather than the 66% he got. Still I would expect the results to be near instant for an indexed field, so something isn't right. I'll update if / when I figure it out. For now I'm moving on, since even the unindexed speed is good enough for my current usage. This is just really weird to see it so slow with indexes.
import RealmSwift
class TimeIt {
let val = DispatchTime.now()
func elapsed() -> DispatchTimeInterval {
return val.distance(to: DispatchTime.now())
}
static func time(_ desc: String, aclosure: () -> Void) {
let t = TimeIt()
aclosure()
print("\(desc) took: \(Double(t.elapsed().nanoseconds) / 1000000.0) ms")
}
}
class RealmIndexed: Object {
#Persisted var id = UUID().uuidString
#Persisted(indexed: true) var val: Int = 0
}
class RealmUnindexed: Object {
#Persisted var id = UUID().uuidString
#Persisted var val: Int = 0
}
func generateObjs(_ hundredsOfThousands: Int = 1) {
let realm = try! Realm()
var objs: [RealmIndexed] = []
for _ in 0..<hundredsOfThousands {
for i in 0..<100_000 {
let obj = RealmIndexed()
obj.val = i
objs.append(obj)
}
}
try! realm.write {
realm.add(objs)
}
var objs2: [RealmUnindexed] = []
for _ in 0..<hundredsOfThousands {
for i in 0..<100_000 {
let obj = RealmUnindexed()
obj.val = i
objs2.append(obj)
}
}
try! realm.write {
realm.add(objs2)
}
}
func baseCountIndexed() -> Int {
return (try! Realm().objects(RealmIndexed.self)).count
}
func baseCountUnindexed() -> Int {
return (try! Realm().objects(RealmUnindexed.self)).count
}
func getCountIndexedObjsViaFilterString(_ minVal: Int = 50000) -> Int {
let count = (try! Realm().objects(RealmIndexed.self).filter("val >= %#", minVal)).count
return count
}
func getCountUnindexedObjsViaFilterString(_ minVal: Int = 50000) -> Int {
let count = (try! Realm().objects(RealmUnindexed.self).filter("val >= %#", minVal)).count
return count
}
func getCountIndexedObjsViaWhereClosure(_ minVal: Int = 50000) -> Int {
let count = (try! Realm().objects(RealmIndexed.self).where { $0.val >= minVal }).count
return count
}
func getCountUnindexedObjsViaWhereClosure(_ minVal: Int = 50000) -> Int {
let count = (try! Realm().objects(RealmUnindexed.self).where { $0.val >= minVal }).count
return count
}
func testRealmSpeed() {
TimeIt.time("realm init6") { _ = try! Realm() }
TimeIt.time("baseCountIndexed") { print(baseCountIndexed()) }
TimeIt.time("baseCountUnindexed") { print(baseCountUnindexed()) }
TimeIt.time("getCountIndexedObjsViaFilterString") { print(getCountIndexedObjsViaFilterString()) }
TimeIt.time("getCountIndexedObjsViaWhereClosure") { print(getCountIndexedObjsViaWhereClosure()) }
TimeIt.time("getCountUnindexedObjsViaFilterString") { print(getCountUnindexedObjsViaFilterString()) }
TimeIt.time("getCountUnindexedObjsViaWhereClosure") { print(getCountUnindexedObjsViaWhereClosure()) }
}
generateObjs(10)
testRealmSpeed()
This is not exactly an answer but perhaps additional info.
I don't think you're doing anything wrong but perhaps a simpler test will be more revealing. I set up two similar objects, one using indexing on a val property and one not. Testing for equality; val == 5, here's the setup:
For brevity, I'm omitting the writing code but it creates 1 Million of each object containing the values 5 and 9 e.g. Realm will contain a million indexed 5,9, 5,9, 5,9 etc and a million not indexed 5,9, 5,9 etc. (5 & 9 are just arbitrary numbers I picked)
And then a function to test each object type. I queried for '5' so it would return a 1/2 million results
func testNotIndexed() {
Task {
let realm = Realm()
let startTime = Date()
let results = try await realm.objects(NotIndexedClass.self).where { $0.val == 5 }
let elapsed = Date().timeIntervalSince(startTime)
print("Not Indexed took: \(elapsed * 1000) ms")
}
}
func testIndexed() {
Task {
let realm = Realm()
let startTime = Date()
let results = try await realm.objects(IndexedClass.self).where { $0.val == 5 }
let elapsed = Date().timeIntervalSince(startTime)
print("Indexed took: \(elapsed * 1000) ms")
}
}
and the repeatable results
Not Indexed took: 1.2680292129516602 ms
Indexed took: 0.44596195220947266 ms
So the indexed query took roughly 1/3 the time.
If the test parameters are changed to be objects containing numbers from 0 to 999,999, and then query for all numbers > 50,000 (not 500k to increase the returned dataset size), the results are similar.

What does the reduce(_:_:) function do in Swift? [duplicate]

This question already has answers here:
What is the reduce() function doing, in Swift
(4 answers)
Closed 9 months ago.
Here is a piece of code I don't understand. This code uses swift's reduce(::) function along with the closure which I am having trouble to understand. What are the values set in maxVerticalPipCount and maxHorizontalPipCount? Are they 5 and 2 respectively?
let pipsPerRowForRank = [[0], [1], [1,1], [1,1,1], [2,2], [2,1,2],
[2,2,2], [2,1,2,2], [2,2,2,2], [2,2,1,2,2],
[2,2,2,2,2]]
let maxVerticalPipCount = CGFloat(pipsPerRowForRank.reduce(0) { max($1.count, $0) })
let maxHorizontalPipCount = CGFloat(pipsPerRowForRank.reduce(0) { max($1.max() ?? 0, $0) })
By the way, if you’re wondering what precisely reduce does, you can always refer to the source code, where you can see the actual code as well as a nice narrative description in the comments.
But the root of your question is that this code is not entirely obvious. I might suggest that if you’re finding it hard to reason about the code snippet, you can replace the opaque shorthand argument names, $0 and $1, with meaningful names, e.g.:
let verticalMax = pipsPerRowForRank.reduce(0) { previousMax, nextArray in
max(nextArray.count, previousMax)
}
let horizontalMax = pipsPerRowForRank.reduce(0) { previousMax, nextArray in
max(nextArray.max() ?? 0, previousMax)
}
By using argument names that make the functional intent more clear, it often is easier to grok what the code is doing. IMHO, especially when there are multiple arguments, using explicit argument names can make it more clear.
That having been said, I’d probably not use reduce and instead do something like:
let verticalMax = pipsPerRowForRank
.lazy
.map { $0.count }
.max() ?? 0
To my eye, that makes the intent extremely clear, namely that we’re counting how many items are in each sub-array and returning the maximum count.
Likewise, for the horizontal one:
let horizontalMax = pipsPerRowForRank
.lazy
.flatMap { $0 }
.max() ?? 0
Again, I think that’s clear that we’re creating a flat array of the values, and then getting the maximum value.
And, in both cases, we’re using lazy to avoid building interim structures (in case our arrays were very large), but evaluating it as we go along. This improves memory characteristics of the routine and the resulting code is more efficient. Frankly, with an array of arrays this small, lazy isn’t needed, but I include it for your reference.
Bottom line, the goal with functional patterns is not to write code with the fewest keystrokes possible (as there are more concise renditions we could have written), but rather to write efficient code whose intent is as clear as possible with the least amount of cruft. But we should always be able to glance at the code and reason about it quickly. Sometimes if further optimization is needed, we’ll make a conscious decision to sacrifice readability for performance reasons, but that’s not needed here.
This is what the reduce functions do here
var maxVerticalPipCount:CGFloat = 0
for rark in pipsPerRowForRank {
if CGFloat(rark.count) > maxVerticalPipCount {
maxVerticalPipCount = CGFloat(rark.count)
}
}
var maxHorizontalPipCount:CGFloat = 0
for rark in pipsPerRowForRank {
if CGFloat(rark.max() ?? 0) > maxHorizontalPipCount {
maxHorizontalPipCount = CGFloat(rark.max() ?? 0)
}
}
You shouldn't use reduce(::) function for finding the max value. Use max(by:)
function like this
let maxVerticalPipCount = CGFloat(pipsPerRowForRank.max { $0.count < $1.count }?.count ?? 0)
let maxHorizontalPipCount = CGFloat(pipsPerRowForRank.max { ($0.max() ?? 0) < ($1.max() ?? 0) }?.max() ?? 0)
The reduce function loops over every item in a collection, and combines them into one value. Think of it as literally reducing multiple values to one value. [Source]
From Apple Docs
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
In your code,
maxVerticalPipCount is iterating through the whole array and finding the max between count of 2nd element and 1st element of each iteration.
maxHorizontalPipCount is finding max of 2nd element's max value and first element.
Try to print each element inside reduce function for better understandings.
let maxVerticalPipCount = pipsPerRowForRank.reduce(0) {
print($0)
return max($1.count, $0)
}
Reduce adds together all the numbers in an array opens a closure and really do whatever you tell it to return.
let pipsPerRowForRank = [[1,1], [2,2,2]]
let maxVerticalPipCount = CGFloat(pipsPerRowForRank.reduce(0) {
max($1.count, $0)})
Here it starts at 0 at reduce(0) and loops through the full array. where it takes the highest value between it's previous value it's in process of calculating and the number of items in the subarray. In the example above the process will be:
maxVerticalPipCount = max(2, 0)
maxVerticalPipCount = max(3, 2)
maxVerticalPipCount = 3
As for the second one
let pipsPerRowForRank = [[1,2], [1,2,3], [1,2,3,4], []]
let maxHorizontalPipCount = CGFloat(pipsPerRowForRank.reduce(0) {
max($1.max() ?? 0, $0)})
Here we instead of checking count of array we check the max value of the nested array, unless it's empty, the it's 0. So here goes this one:
let maxHorizontalPipCount = max(2, 0)
let maxHorizontalPipCount = max(3, 2)
let maxHorizontalPipCount = max(4, 3)
let maxHorizontalPipCount = max(0, 4)
let maxHorizontalPipCount = 4
Example With Swift 5,
enum Errors: Error {
case someError
}
let numbers = [1,2,3,4,5]
let inititalValue = 0
let sum = numbers.reduce(Result.success(inititalValue)) { (result, value) -> Result<Int, Error> in
if let initialValue = try? result.get() {
return .success(value + initialValue)
} else {
return .failure(Errors.someError)
}
}
switch sum {
case .success(let totalSum):
print(totalSum)
case .failure(let error):
print(error)
}

Swift for loop with stride that references itself [duplicate]

...or how can I use the index inside the for loop condition
Hey people
Since we're left with no c style for loops in swift 3 I can't seem to find a way to express a bit more complex for loops so maybe you can help me out.
If I were to write this
for(int i=5; num/i > 0; i*=5)
in swift 3 how would I do that?
The closes I came by was:
for i in stride(from: 5, through: num, by: 5) where num/i > 0
but this will of course iterate 5 chunks at a time instead if i being: 5, 25, 125 etc.
Any ideas?
Thanks
Using a helper function (originally defined at Converting a C-style for loop that uses division for the step to Swift 3)
public func sequence<T>(first: T, while condition: #escaping (T)-> Bool, next: #escaping (T) -> T) -> UnfoldSequence<T, T> {
let nextState = { (state: inout T) -> T? in
// Return `nil` if condition is no longer satisfied:
guard condition(state) else { return nil }
// Update current value _after_ returning from this call:
defer { state = next(state) }
// Return current value:
return state
}
return sequence(state: first, next: nextState)
}
you can write the loop as
let num = 1000
for i in sequence(first: 5, while: { num/$0 > 0 }, next: { $0 * 5 }) {
print(i)
}
A simpler solution would be a while-loop:
var i = 5
while num/i > 0 {
print(i)
i *= 5
}
but the advantage of the first solution is that the scope of the loop variable is limited to the loop body, and that the loop variable is a constant.
Swift 3.1 will provide a prefix(while:) method for sequences,
and then the helper function is no longer necessary:
let num = 1000
for i in sequence(first: 5, next: { $0 * 5 }).prefix(while: { num/$0 > 0 }) {
print(i)
}
All of above solutions are "equivalent" to the given C loop.
However, they all can crash if num is close to Int.max
and $0 * 5 overflows. If that is an issue then you have to check
if $0 * 5 fits in the integer range before doing the multiplication.
Actually that makes the loop simpler – at least if we assume that
num >= 5 so that the loop is executed at least once:
for i in sequence(first: 5, next: { $0 <= num/5 ? $0 * 5 : nil }) {
print(i)
}
For completeness: an alternative to the while loop approach is using an AnyIterator:
let num = 1000
var i = 5
for i in AnyIterator<Int>({
return i <= num ? { defer { i *= 5 }; return i }() : nil
}) {
// note that we choose to shadow the external i variable name,
// such that any access to i within this loop will only refer
// to the loop local immutable variable i.
print(i)
// e.g. i += 1 not legal, i refers to a constant here!
} /* 5
25
125
625 */
This method suffers from the same drawback as the while loop in that the loop "external" i variable persists outside and after the scope of the loop block. This external i variable is not, however, the i variable that is accessible within the loop body, as we let the loop body variable i shadow the external one, limiting access to i within the body to the immutable, temporary (loop scope local) one.

Express for loops in swift with dynamic range

...or how can I use the index inside the for loop condition
Hey people
Since we're left with no c style for loops in swift 3 I can't seem to find a way to express a bit more complex for loops so maybe you can help me out.
If I were to write this
for(int i=5; num/i > 0; i*=5)
in swift 3 how would I do that?
The closes I came by was:
for i in stride(from: 5, through: num, by: 5) where num/i > 0
but this will of course iterate 5 chunks at a time instead if i being: 5, 25, 125 etc.
Any ideas?
Thanks
Using a helper function (originally defined at Converting a C-style for loop that uses division for the step to Swift 3)
public func sequence<T>(first: T, while condition: #escaping (T)-> Bool, next: #escaping (T) -> T) -> UnfoldSequence<T, T> {
let nextState = { (state: inout T) -> T? in
// Return `nil` if condition is no longer satisfied:
guard condition(state) else { return nil }
// Update current value _after_ returning from this call:
defer { state = next(state) }
// Return current value:
return state
}
return sequence(state: first, next: nextState)
}
you can write the loop as
let num = 1000
for i in sequence(first: 5, while: { num/$0 > 0 }, next: { $0 * 5 }) {
print(i)
}
A simpler solution would be a while-loop:
var i = 5
while num/i > 0 {
print(i)
i *= 5
}
but the advantage of the first solution is that the scope of the loop variable is limited to the loop body, and that the loop variable is a constant.
Swift 3.1 will provide a prefix(while:) method for sequences,
and then the helper function is no longer necessary:
let num = 1000
for i in sequence(first: 5, next: { $0 * 5 }).prefix(while: { num/$0 > 0 }) {
print(i)
}
All of above solutions are "equivalent" to the given C loop.
However, they all can crash if num is close to Int.max
and $0 * 5 overflows. If that is an issue then you have to check
if $0 * 5 fits in the integer range before doing the multiplication.
Actually that makes the loop simpler – at least if we assume that
num >= 5 so that the loop is executed at least once:
for i in sequence(first: 5, next: { $0 <= num/5 ? $0 * 5 : nil }) {
print(i)
}
For completeness: an alternative to the while loop approach is using an AnyIterator:
let num = 1000
var i = 5
for i in AnyIterator<Int>({
return i <= num ? { defer { i *= 5 }; return i }() : nil
}) {
// note that we choose to shadow the external i variable name,
// such that any access to i within this loop will only refer
// to the loop local immutable variable i.
print(i)
// e.g. i += 1 not legal, i refers to a constant here!
} /* 5
25
125
625 */
This method suffers from the same drawback as the while loop in that the loop "external" i variable persists outside and after the scope of the loop block. This external i variable is not, however, the i variable that is accessible within the loop body, as we let the loop body variable i shadow the external one, limiting access to i within the body to the immutable, temporary (loop scope local) one.

For loop based on exponential increases [duplicate]

...or how can I use the index inside the for loop condition
Hey people
Since we're left with no c style for loops in swift 3 I can't seem to find a way to express a bit more complex for loops so maybe you can help me out.
If I were to write this
for(int i=5; num/i > 0; i*=5)
in swift 3 how would I do that?
The closes I came by was:
for i in stride(from: 5, through: num, by: 5) where num/i > 0
but this will of course iterate 5 chunks at a time instead if i being: 5, 25, 125 etc.
Any ideas?
Thanks
Using a helper function (originally defined at Converting a C-style for loop that uses division for the step to Swift 3)
public func sequence<T>(first: T, while condition: #escaping (T)-> Bool, next: #escaping (T) -> T) -> UnfoldSequence<T, T> {
let nextState = { (state: inout T) -> T? in
// Return `nil` if condition is no longer satisfied:
guard condition(state) else { return nil }
// Update current value _after_ returning from this call:
defer { state = next(state) }
// Return current value:
return state
}
return sequence(state: first, next: nextState)
}
you can write the loop as
let num = 1000
for i in sequence(first: 5, while: { num/$0 > 0 }, next: { $0 * 5 }) {
print(i)
}
A simpler solution would be a while-loop:
var i = 5
while num/i > 0 {
print(i)
i *= 5
}
but the advantage of the first solution is that the scope of the loop variable is limited to the loop body, and that the loop variable is a constant.
Swift 3.1 will provide a prefix(while:) method for sequences,
and then the helper function is no longer necessary:
let num = 1000
for i in sequence(first: 5, next: { $0 * 5 }).prefix(while: { num/$0 > 0 }) {
print(i)
}
All of above solutions are "equivalent" to the given C loop.
However, they all can crash if num is close to Int.max
and $0 * 5 overflows. If that is an issue then you have to check
if $0 * 5 fits in the integer range before doing the multiplication.
Actually that makes the loop simpler – at least if we assume that
num >= 5 so that the loop is executed at least once:
for i in sequence(first: 5, next: { $0 <= num/5 ? $0 * 5 : nil }) {
print(i)
}
For completeness: an alternative to the while loop approach is using an AnyIterator:
let num = 1000
var i = 5
for i in AnyIterator<Int>({
return i <= num ? { defer { i *= 5 }; return i }() : nil
}) {
// note that we choose to shadow the external i variable name,
// such that any access to i within this loop will only refer
// to the loop local immutable variable i.
print(i)
// e.g. i += 1 not legal, i refers to a constant here!
} /* 5
25
125
625 */
This method suffers from the same drawback as the while loop in that the loop "external" i variable persists outside and after the scope of the loop block. This external i variable is not, however, the i variable that is accessible within the loop body, as we let the loop body variable i shadow the external one, limiting access to i within the body to the immutable, temporary (loop scope local) one.