Search code examples
swiftsyntaxsubscript

Error: Cannot subscript a value of type 'X' with ...'


Error: Cannot subscript a value of type '[CustomClass]' with an index of type '(safe: Int)'

class CustomClass {
  let value: String
  init(value: String) {
    self.value = value
  }
}

extension Collection {

  subscript(safe: Int) -> Element? {
    if safe > count-1 {
      return nil
    }
    return self[safe]
  }
}

let steps: [CustomClass] = []

if let step = steps[safe: 4] { // error here
}

Why is this happening?


Solution

  • Note that besides the subscript parameter issue already mentioned in comments by @Hamish there are a few other issues in your code: ArraySlice also conforms to RandomAccessCollection so just checking the array count doesn't guarantee it is a safe index. You should add a guard statement to check if the indices property contains the Index. You should also change your subscript parameter to Index instead of Int:

    class CustomClass {
        let value: Int
        init(value: Int) {
            self.value = value
        }
    }
    
    extension Collection  {
        subscript(safe index: Index) -> Element? {
            guard indices.contains(index) else {
                return nil
            }
            return self[index]
            // or simply
            // return indices.contains(index) ? self[index] : nil
        }
    }
    

    Playground testing:

    let steps = [CustomClass(value: 0),CustomClass(value: 1),CustomClass(value: 2),CustomClass(value: 3),CustomClass(value: 4),CustomClass(value: 5),CustomClass(value: 6)]
    
    if let step6 = steps[safe: 6] {
        print(step6.value)  // 6
    }
    
    let stepsSlice = steps[0...4]
    let step6 = stepsSlice[safe: 6]
    print(step6?.value)   // nil