swift - 无法为值添加下标

标签 swift

我想设置一个下标,这样我总是能够在 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/

相关文章:

Swift:重用闭包定义(使用类型别名)

ios - 在此图像上执行某些操作后异步图像加载 - 滚动时图像更改为错误图像

ios - 如何在 Swift 中使用自定义图像作为 UIButton

ios - curl 命令到 NSURLRequest Swift

Visual Studio 2015 中的 C#、Swift 和 Android

ios - RxDataSources Collection View 单元格始终使用淡入淡出来插入单元格动画,无法更改为不同的动画

ios - 如何向用户显示 UITableViewCell 滑动操作的预览

ios - 突然完全停止接收 firebase 通知

ios - 如何使用 RxSwift 和 Alamofire 下载图像?

ios - 如何使 SwiftUI 中的背景半透明?