1

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.

Michel
  • 10,303
  • 17
  • 82
  • 179

2 Answers2

3

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])
Sweeper
  • 213,210
  • 22
  • 193
  • 313
3
let patternArray = [true,true,false,true,true,false,true,true]
var resultArray = [Bool]()
resultArray = Array(patternArray[0..<4])

Subscripting an Array with an index of type CountableRange returns ArraySlice, which helps to "share" the underlying memory with the original Array. To be able to assign ArraySlice to the variable with a type of Array, all the values must be copied as an independent Array. The simplest way is to create the Array as is shown in my example, with the appropriate constructor.

var arr = [1,2,3,4]
let arrslice = arr[1..<3]
for i in arrslice.indices {
    arr[i] = 0
}
print(arr, arrslice)

prints

[1, 0, 0, 4] [2, 3]

even more interesting :-)

arr[1..<3] = arrslice
print(arr)

prints

[1, 2, 3, 4]
user3441734
  • 16,722
  • 2
  • 40
  • 59
  • While this code may answer the question, providing additional [context](https://meta.stackexchange.com/q/114762) regarding _how_ and/or _why_ it solves the problem would improve the answer's long-term value. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add an explanation, and give an indication of what limitations and assumptions apply. It also doesn't hurt to mention why this answer is more appropriate than others. – Dev-iL Jun 25 '17 at 09:31
  • @Dev-iL I did ... sorry – user3441734 Jun 25 '17 at 09:59
  • No need to be sorry :) Your answer was acceptable, but now it is better by far! – Dev-iL Jun 25 '17 at 10:01