我想设置一个下标,这样我总是能够在 swift 中安全地使用数组
let array = ["a", "b", "c", "d"]
let sliceOfArray = array[1...3]
extension Collection {
subscript(test: Index) -> Element? {
return indices.contains(test) ? self[test] : nil
}
}
sliceOfArray[test: 0]
这给了我错误 Cannot subscript a value of type 'ArraySlice<String>' with an index of type '(test: Int)'
那么我怎样才能让这个下标运行呢?
最佳答案
Swift likes to be safe, but one problematic area can be reading from arrays and dictionaries. In the case of dictionaries, reading a missing key will return nil rather than the value you might have expected, but in the case of arrays it’s worse: your app will crash. More details
尝试这样
extension Collection {
subscript(safe test: Index) -> Element? {
return indices.contains(test) ? self[test] : nil
}
}
关于swift - 无法为值添加下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58953800/