Swift Array 可选类型和下标(Beta 3) [英] Swift Array optional Type and subscripting (Beta 3)

查看:48
本文介绍了Swift Array 可选类型和下标(Beta 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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?

推荐答案

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

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

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

和调用:

exchange(&date, 0, 2)

您也可以使用 var 但这只会允许在子例程中修改数组.Beta 3 的重大变化是让数组真正按值传递,而不是在某些时候只是按值传递,但其他时候则不然.

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.

这篇关于Swift Array 可选类型和下标(Beta 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆