斯威夫特通用阵列“不相同”错误 [英] Swift Generic Array 'not identical' error

查看:148
本文介绍了斯威夫特通用阵列“不相同”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是要通过显然已经过时,因为Beta3中的一些斯威夫特TUTS ...

I'm just going through some Swift tuts that are obviously already outdated as of Beta3 ...

func exchange<T>(data:[T], i:Int, j:Int)
{
    let temp = data[i];
    data[i] = data[j];
    data[j] = temp;
}

操场告诉我:

错误:@lvalue $ T8是不相同于T

Error: @lvalue $T8 is not identical to T.

我如何改变它,使其工作?

How do I change it to make it work?

推荐答案

在斯威夫特数组是值类型。这意味着,数据时,传递到你的兑换方法,但您要修改副本影响被复制原始版本。相反,你应该做两件事情之一:

Arrays in Swift are value types. That means that data is copied when passed into your exchange method, but you are trying to modify the copy to affect the original version. Instead you should do one of two things:

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

然后调用它时,你必须添加一个&安培; 呼叫前:

var myArray = ["first", "second"]
exchange(&myArray, 0, 1)

2。返回数组的副本(推荐)

func exchange<T>(data:[T], i:Int, j:Int) -> [T]
{
    var newData = data
    newData[i] = data[j]
    newData[j] = data[i]
    return newData
}

我推荐这种方式比在出参数,因为在输出参数创建更复杂的状态。你有两个变量指向和潜在操纵同一块内存。如果兑换决定做一个单独的线程的工作?还有一个原因,苹果决定把数组值类型,使用出颠覆了。最后,返回一个拷贝更接近函数编程它是一种很有前途的方向上夫特可以移动。我们在我们的应用程序越少状态下,更少的错误,我们将创建(一般)。

I recommend this way over the in-out parameter because in-out parameters create more complicated state. You have two variables pointing to and potentially manipulating the same piece of memory. What if exchange decided to do its work on a separate thread? There is also a reason that Apple decided to make arrays value types, using in-out subverts that. Finally, returning a copy is much closer to Functional Programming which is a promising direction that Swift can move. The less state we have in our apps, the fewer bugs we will create (in general).

这篇关于斯威夫特通用阵列“不相同”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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