Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-06-25

Swift Gotcha: Surprising behaviour for empty array slices in Swift

Today I stumbled over some surprising behaviour of the array slice operations.
I wanted to assign one slice to another but of course had to check what would happen for zero slices. Turns out zero slices work fine if you do them right, like this:

var arr1 = [1, 2, 3, 4]
var arr2 = [5, 6, 7]

arr1[1 ..< 1] = arr2[1 ..< 1]


println(arr1) // Prints "[1, 2, 3, 4]"

However if you do them wrong, things grind to halt. And not in the nicest way.
This is wrong:

var arr1 = [1, 2, 3, 4]
var arr2 = [5, 6, 7]

arr1[1 ... 0] = arr2[1 ... 0]

println(arr1)  // Prints nothing in playground

I did not expect there to be contextual difference between the two, but apparently there is.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment