使用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
andlast
properties for safe access to the value of the array’s first and last elements. If the array is empty, these properties arenil
....
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/