Swift Array可选类型和下标(Beta 3)

时间:2022-11-24 11:12:32

I'm following the 2014 WWDC tutorial 408: Swift Playgrounds using XCode Beta 3 (30 minutes in). The Swift syntax has changed since Beta 2.

我正在关注2014年WWDC教程408:使用XCode Beta 3的Swift Playgrounds(30分钟)。自Beta 2以来,Swift语法已经发生了变化。

var data = [27, 46, 96, 79, 56, 85, 45, 34, 2, 57, 29, 66, 99, 65, 66, 40, 40, 58, 87, 64]

func exchange<T>(data: [T], i: Int, j: Int) {
    let temp = data[i]
    data[i] = data[j]  // Fails with error '@lvalue $T8' is not identical to 'T'
    data[j] = temp     // Fails with error '@lvalue $T5' is not identical to 'T'
}

exchange(data, 0 , 2)
data

Why I can't modify a mutable integer array in this way?

为什么我不能以这种方式修改可变整数数组?

2 个解决方案

#1


10  

Because subroutine parameters are implicitly defined with let hence, non mutable. Try changing the declaration to:

因为子例程参数是使用let隐式定义的,因此不可变。尝试将声明更改为:

func exchange<T>(inout data: [T], i: Int, j: Int) {

and the invocation to:

并调用:

exchange(&date, 0, 2)

You can also use var but that would only allow the array to be modified within the subroutine. The big change for beta 3 was to make arrays really pass by value instead of just kind of sorta pass by value some of the time, but not the rest.

您也可以使用var,但这只允许在子例程中修改数组。 beta 3的最大变化是使数组真正通过值传递,而不仅仅是在某些时候通过值传递,而不是其余的。

#2


2  

@David answer is correct, let me explain why: arrays (as well as dictionaries and strings) are value types (structs) and not reference types. When a value type has to be passed to a function, a copy of it is created, and the function works on that copy.

@David的答案是正确的,让我解释一下原因:数组(以及字典和字符串)是值类型(结构)而不是引用类型。当必须将值类型传递给函数时,会创建它的副本,并且该函数适用于该副本。

By using the inout modifier, the original array is passed instead, so in that case it's possible to make changes on it.

通过使用inout修饰符,相反传递原始数组,因此在这种情况下可以对其进行更改。

#1


10  

Because subroutine parameters are implicitly defined with let hence, non mutable. Try changing the declaration to:

因为子例程参数是使用let隐式定义的,因此不可变。尝试将声明更改为:

func exchange<T>(inout data: [T], i: Int, j: Int) {

and the invocation to:

并调用:

exchange(&date, 0, 2)

You can also use var but that would only allow the array to be modified within the subroutine. The big change for beta 3 was to make arrays really pass by value instead of just kind of sorta pass by value some of the time, but not the rest.

您也可以使用var,但这只允许在子例程中修改数组。 beta 3的最大变化是使数组真正通过值传递,而不仅仅是在某些时候通过值传递,而不是其余的。

#2


2  

@David answer is correct, let me explain why: arrays (as well as dictionaries and strings) are value types (structs) and not reference types. When a value type has to be passed to a function, a copy of it is created, and the function works on that copy.

@David的答案是正确的,让我解释一下原因:数组(以及字典和字符串)是值类型(结构)而不是引用类型。当必须将值类型传递给函数时,会创建它的副本,并且该函数适用于该副本。

By using the inout modifier, the original array is passed instead, so in that case it's possible to make changes on it.

通过使用inout修饰符,相反传递原始数组,因此在这种情况下可以对其进行更改。