Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 662
Jean Lebrument Avatar asked Oct 10 '14 09:10

Jean Lebrument


2 Answers

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()!
    ...
  }
}
like image 195
Patrick Beard Avatar answered Oct 06 '22 00:10

Patrick Beard


- I can think of a work around which can be implemented here, and its the use of map function of Array.

Iteration over each Elements:

let arr = [1, 2, 3, 4, 5]
arr.map { a in print("\(a + 1) ") }

Output:

2 3 4 5 6

- So in this way you can achieve the iteration over each element of the Array in Swift.

like image 26
Kumar Vivek Mitra Avatar answered Oct 05 '22 23:10

Kumar Vivek Mitra