Error: Cannot subscript a value of type '[CustomClass]' with an index of type '(safe: Int)'
错误:不能为'[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
}
Why is this happening?
为什么会这样?
1 个解决方案
#1
1
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
:
注意,除了@Hamish在注释中提到的下标参数问题之外,代码中还有其他一些问题:ArraySlice也符合RandomAccessCollection,因此仅检查数组计数并不保证它是一个安全的索引。您应该添加一个guard语句来检查索引属性是否包含索引。您还应该将下标参数改为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
}
}
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
#1
1
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
:
注意,除了@Hamish在注释中提到的下标参数问题之外,代码中还有其他一些问题:ArraySlice也符合RandomAccessCollection,因此仅检查数组计数并不保证它是一个安全的索引。您应该添加一个guard语句来检查索引属性是否包含索引。您还应该将下标参数改为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
}
}
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