arrays - 初学者 : When working with arrays, 为什么这个有效但这个不行?

标签 arrays swift

使用colorsArray.last的可以工作,但使用下标语法的则不行,例如colorsArray[2]。您能为我理解这一点提供任何帮助,那就太好了。我正在自学 Swift,所以我来这里是为了解答我的问题。

let colorsArray = ["Red", "Green", "Blue"]


if let method2 = colorsArray.last {
    print(method2)
}


if let method2 = colorsArray[2] {
    print(method2)
}

最佳答案

问题在于,对于数组,下标运算符不会返回 optional ,因此使用像 if let 这样的解包结构来解包它是没有意义的。

尝试 let foo = colorArray[42],其中索引超出范围。它不会返回 nil,而是会因“下标超出范围”错误而崩溃。如the documentation说(强调):

Use the first and last properties for safe access to the value of the array’s first and last elements. If the array is empty, these properties are nil.

...

You can access individual array elements through a subscript. The first element of a nonempty array is always at index zero. You can subscript an array with any integer from zero up to, but not including, the count of the array. Using a negative number or an index equal to or greater than count triggers a runtime error.

因此,last 提供安全访问,返回一个可选值,但下标运算符不返回可选值,而且如果您提供无效索引,也不会提供安全访问。

关于arrays - 初学者 : When working with arrays, 为什么这个有效但这个不行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60743469/

相关文章:

java - Java 中的字长

swift - 如何使用约束/布局复制/复制场景

swift - 在 Firebase 中创建一个实时观察器,始终使用 Swift 更新更改

带音量包络的 iOS 音频采样器

arrays - 从自定义 tableViewCell 中的数组中删除项目

javascript - 打印从数组的索引值中获取的值的数量

javascript - for 循环和索引数组不起作用

swift - 如何将数据从 tableview 传递到不同的 uiviewcontroller

ios - BLKFlexibleHeightBar 行为定义器不符合 UITableViewDelegate

ios - Swift 2 .plist dictArray 到远程 Json 数组错误