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 ?
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()!
...
}
}
- 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With