For x in 1..3..10 ? Yes, please.

There’s some syntax in MATLAB I always really liked. If you type 1:10, you get an array (or “vector”) of [1,2,3,4,5,6,7,8,9,10]. If you want to increment the values by something other than 1, that’s easy. Type 1:3:10 and you get [1,4,7,10].

When I first learned of Swift’s Range syntax, I was happy to see that I could create arrays in a similar fashion in Swift… sort of. The only way to use an increment value other than 1 was the rather long-winded stride syntax. Now that C-style for loops are on their way out of Swift1, it got me thinking… wouldn’t it be great to have some for loop syntax that looked like this:

for i in 1..3..10{
    // Your code here
}

Well, turns out this is pretty straightforward and a great opportunity to get familiar with custom operators. Here’s all you need:

infix operator .. {associativity left}
func .. (lhs: Int, rhs: Int) -> (Int,Int){
    return (lhs, rhs)
}
func .. (lhs: (Int, Int), rhs: Int) -> [Int]{
    return Array(lhs.0.stride(through: rhs, by: lhs.1))
}

infix operator ..< {associativity left}
func ..< (lhs: (Int, Int), rhs: Int) -> [Int]{
    return Array(lhs.0.stride(to: rhs, by: lhs.1))
}

That’s it! Paste that into a playground with a print(1..3..10) or print(100..100..<400) and you're on your way to some Swifty strides! To see examples in MATLAB and using Swift's stride functions, visit https://github.com/alexjamesa/SwiftyStride. Please share any feedback or suggestions below and you can find me on twitter at @leakywellington.

1Great video of what's new in Swift 2.2 at hackingwithswift.com.

Leave a Reply

Your email address will not be published. Required fields are marked *