Search code examples
swift3sub-array

Subarrays not working in Swift 3


In Swift 3 I have two variables declared like this:

let patternArray = [true,true,false,true,true,false,true,true]
var resultArray = [Bool]()

Later in my code I have this, to get part of the array:

resultArray = patternArray [0..<4]

Whe compliling I get this error message:

Cannot subscript a value of type '[Bool]' with an index of type 'CountableRange<Int>'

I have no idea why. Am I making some obvious mistake?

I am using Xcode Version 8.3.2.

Moreover I have checked that this kind of syntax works in Playground.


Solution

  • This is because subscripting using a range gives you an ArraySlice<T>.

    You are trying to assign an ArraySlice<Bool> to a [Bool], which results in a type mismatch. The swift compiler is apparently too stupid to point this out. The swift compiler searches for subscripts that returns a [Bool] but can't find any so it tells you that you can't subscript... which is a pretty weird logic. Maybe this will get fixed in Swift 4.

    Just initialise a new [Bool]:

    resultArray = [Bool](patternArray[0..<4])