Jean Lebrument Jean Lebrument - 4 months ago 24
Swift Question

Accessing element of an array with iterator instead of position in Swift

I would like to know if there are iterators for array in Swift, like in CPP, which permits to avoid the using of position to access to the next element of an array.

Actually, I use position + 1 in my array to access its next element:

var array = ["a", "b", "c", "d"]

func arrayToString(success : String -> Void)
{
var str = String()

var myFunc : (Int -> Void)!

myFunc = {

if $0 < array.count
{
str += array[$0]

myFunc($0 + 1)
}
else
{
success(str)
}
}

myFunc(0)
}

arrayToString({

println($0)

})


I'm looking for a solution usable like this:

var array = ["a", "b", "c", "d"]

func arrayToString(success : String -> Void)
{
var str = String()

var myFunc : (Iterator -> Void)!

myFunc = {

if $0 != nil
{
str += array[$0]

myFunc($0.next)
}
else
{
success(str)
}
}

myFunc(array.first)
}

arrayToString({

println($0)

})


Any suggestions ?

Answer

What you want is to use a generator:

var array = ["a", "b", "c", "d"]
var g = array.generate()
var str = String()
for (var i = g.next(); i != nil; i = g.next()) {
  str += i!
}

This is very handy when you want to parse command line arguments:

var args = Process.arguments.generate()
while let arg = args.next() {
  if (arg == "--output") {
    let output = args.next()!
    ...
  }
}

In Swift 3, this now becomes:

var args = Process.arguments.makeIterator()
while let arg = args.next() {
  if (arg == "--output") {
    let output = args.next()!
    ...
  }
}