错误:无法使用...

时间:2018-01-13 22:45:44

标签: swift syntax subscript

错误:无法下标类型'[CustomClass]'的值,其索引类型为'(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
}

为什么会这样?

1 个答案:

答案 0 :(得分:1)

请注意,除了@Hamish在评论中已经提到的下标参数问题之外,您的代码中还存在一些其他问题:ArraySlice也符合RandomAccessCollection所以只检查数组计数并不能保证这是一个安全的指标。您应该添加guard语句来检查indices属性是否包含Index。您还应将下标参数更改为Index而不是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
    }
}

游乐场测试:

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