31

I'm trying to figure out how to use the Stride features in Swift.

It seems to have changed again, since Xcode 7.0 beta 6.

Previously I could use

let strideAmount = stride(from: 0, to: items.count, by: splitSize)
let sets = strideAmount.map({ clients[$0..<advance($0, splitSize, items.count)] })

Now, despite the code hint I cannot figure out how to use this feature.

Any examples would be helpful thanks.

I've looked at examples, but I cannot come to grips with how to use it. All I get from the Apple Docs are limited.

Thanks

DogCoffee
  • 19,820
  • 10
  • 87
  • 120

2 Answers2

67

It changed a bit, here is the new syntax:

0.stride(to: 10, by: 2)

and

Array(0.stride(to: 10, by: 2)) // is [0, 2, 4, 6, 8]

if you take a look at here, you can see what types conform to the Strideable protocol.

As @RichFox pointed out, in Swift 3.0 the syntax changed back to the original global function form like:

stride(from:0, to: 10, by: 2)
Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
  • 2
    I did not know of SwiftDoc - bonus! Thanks – DogCoffee Aug 25 '15 at 10:14
  • 1
    syntax is now global function again... `stride(from:0, to: 10, by: 2)` for example you can : `for i in stride(from:0, to: 10, by: 2) { print(i) }` – Rich Fox Sep 26 '16 at 02:47
  • `let array = Array(1...10)` or `let array = Array(1..<10)`, @DánielNagy I just want to know the advantages of stride while we can use closed rages and open ranges like I mentioned here. – abhimuralidharan Jun 30 '17 at 08:39
  • 1
    @abhi1992 I did not checked it before, but I think the constructor which you described was added in Swift 3 as well. IMO using `stride` makes sense only if you are not creating a sequence with consecutive elements, otherwise I would use `Array(1...10)` since it's shorter. – Dániel Nagy Jul 01 '17 at 11:23
1

Usage of stride function in swift 4.2

12345
 2345
  345
   45
    5
    5
   45
  345
 2345
12345


for i in 1...5{
    for k in 1...i{
        print(terminator : " ")
    }
    for j in stride(from: i, to: 6, by: 1){
        print(j , terminator : "")
    }

    print(" ")
}
for i in stride(from: 5, to: 0, by: -1)
{
    for k in 1...i{
        print(terminator : " ")
    }
    for j in stride(from: i, to: 6, by: 1){
        print(j,terminator : "")
    }
    print(" ")
}
1 2 3 4 5
 2 3 4 5
  3 4 5
   4 5
    5
    5
   4 5
  3 4 5
 2 3 4 5
1 2 3 4 5
for i in 1...5{
    for k in 0...i{
        print(terminator : " ")
    }
    for j in stride(from: i, to: 6, by: 1){
        print(j , terminator : " ")
    }

    print(" ")
}

for i in stride(from: 6, to: 1, by: -1){
    for k in 1...i{
        print(terminator : " ")
    }
    for j in stride(from: i-1, to: 6, by: 1){
        print(j , terminator : " ")
    }

    print(" ")
}
Ankur Purwar
  • 275
  • 2
  • 9