Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 错误:无法为类型为';的值下标;X';与……和#x27;_Swift_Syntax_Subscript - Fatal编程技术网

Swift 错误:无法为类型为';的值下标;X';与……和#x27;

Swift 错误:无法为类型为';的值下标;X';与……和#x27;,swift,syntax,subscript,Swift,Syntax,Subscript,错误:无法使用类型为“(safe:Int)”的索引为“[CustomClass]”类型的值下标 为什么会发生这种情况?请注意,除了@Hamish在评论中提到的下标参数问题外,代码中还有一些其他问题:ArraySlice也符合RandomAccessCollection,因此仅检查数组计数并不能保证它是一个安全的索引。您应该添加一个guard语句来检查Index属性是否包含Index。您还应该将下标参数更改为Index,而不是Int: class CustomClass { let val

错误:无法使用类型为“(safe:Int)”的索引为“[CustomClass]”类型的值下标


为什么会发生这种情况?

请注意,除了@Hamish在评论中提到的下标参数问题外,代码中还有一些其他问题:
ArraySlice
也符合
RandomAccessCollection
,因此仅检查数组计数并不能保证它是一个安全的索引。您应该添加一个
guard
语句来检查
Index
属性是否包含
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

看见我认为参数nam可能有问题,因为在某些上下文中,“safe”是一个关键字;您需要显式地声明它们,例如
subscript(safe-safe:Int)->Element?
,或者最好是
subscript(safe-index:Int)->Element?
(如Q&A Sulthan链接所示),因为
safe
不是局部变量的好名字。
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