附加到一个空数组给出错误 [英] Appending to an empty array giving error

查看:26
本文介绍了附加到一个空数组给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个空数组来存储形式(Int,Double)的数据.我放弃了将元组直接附加到数组的尝试,因为似乎没有设置 swift 来执行此操作.所以我的代码示例如下所示:

I have created an empty array to store data of the form (Int,Double). I gave up on trying to directly append a tuple to the array, as it seems swift is not set up to do this. So an example of my code looks like this:

var data: [(x: Int,y: Double)] = []
var newDataX: Int = 1
var newDataY: Double = 2.0
data.append(x: newDataX,y: newDataY)

附加行的错误消息是类型 'T' 不符合协议 'IntegerLiteralConvertible' 这让我困惑不已.当我专门附加一个整数和一个双精度时(即 data.append(1,2.0)), 我没有收到错误消息.如果我尝试附加其中一个特定的和其中一个使用变量,无论哪个是变量,我都会收到消息.

The error message for the append line is "Type 'T' does not conform to protocol 'IntegerLiteralConvertible' which confuses me to no end. When I specifically append an integer and a double (ie. data.append(1,2.0)), I do not receive the error message. If I try to append one of the specifically and one of them using a variable I get the message no matter which one is the variable.

我会使用 += 命令只是在数组上附加一个元组,但我理解它的方式,这在 beta5 中不再是一个有效的命令.我没有看到我的代码有什么问题吗?或者有其他方法可以做我想做的事情吗?

I would use the += command just append a tuple onto the array, but I the way I understand it, that is no longer a valid command in beta5. Is there something wrong with my code that I am not seeing? Or is there another way to do what I want to do?

推荐答案

问题在于 x: newDataX, y: newDataY 没有作为单个参数解析 - 而是作为 2 个单独的参数传递到 append 函数,编译器会查找匹配的 append 函数,该函数采用 IntDouble.

The problem is that x: newDataX, y: newDataY is not resolved as a single parameter - instead it's passed as 2 separate parameters to the append function, and the compiler looks for a matching append function taking an Int and a Double.

可以通过在追加前定义元组来解决问题:

You can solve the problem by defining the tuple before appending:

let newData = (x: 1, y: 2.0)
data.append(newData)

或者明确指出参数对是一个元组.元组由括号 (1, 2.0) 包围的列表标识,但不幸的是这不起作用:

or making explicit that the parameters pair is a tuple. A tuple is identified by a list surrounded by parenthesis (1, 2.0), but unfortunately this doesn't work:

data.append( (x: 1, y: 2.0) )

如果你真的需要/想要在一行中追加,你可以使用如下的闭包:

If you really need/want to append in a single line, you can use a closure as follows:

data.append( { (x: newDataX, y: newDataY) }() )

更优雅的解决方案是使用typealias:

A more elegant solution is by using a typealias:

typealias MyTuple = (x: Int, y: Double)

var data: [MyTuple] = []

var newDataX: Int = 1
var newDataY: Double = 2.0

data.append(MyTuple(x: 1, y: 2.0))

这篇关于附加到一个空数组给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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