如何将元组添加到 Swift 数组? [英] How do I add a tuple to a Swift Array?
问题描述
我正在尝试向数组添加一个元组(例如,2 项元组).
I'm trying to add a tuple (e.g., 2-item tuple) to an array.
var myStringArray: (String,Int)[]? = nil
myStringArray += ("One", 1)
我得到的是:
What I'm getting is:
找不到接受提供的+="的重载论据
Could not find an overload for '+=' that accepts the supplied arguments
提示:我试图重载每本参考书的+=":
Hint: I tried to do an overload of the '+=' per reference book:
@assignment func += (inout left: (String,Int)[], right: (String,Int)[]) {
left = (left:String+right:String, left:Int+right+Int)
}
...但没有做对.
有什么想法吗?...解决方案?
Any ideas? ...solution?
推荐答案
由于这仍然是 google 上将元组添加到数组的最佳答案,因此值得注意的是,在最新版本中情况略有变化.即:
Since this is still the top answer on google for adding tuples to an array, its worth noting that things have changed slightly in the latest release. namely:
声明/实例化数组时;类型现在嵌套在大括号内:
when declaring/instantiating arrays; the type is now nested within the braces:
var stuff:[(name: String, value: Int)] = []
复合赋值运算符,+=
,现在用于连接数组;如果添加单个项目,则需要嵌套在数组中:
the compound assignment operator, +=
, is now used for concatenating arrays; if adding a single item, it needs to be nested in an array:
stuff += [(name: "test 1", value: 1)]
还值得注意的是,在包含命名元组的数组上使用 append()
时,您可以提供要添加的元组的每个属性作为 append()代码>:
it also worth noting that when using append()
on an array containing named tuples, you can provide each property of the tuple you're adding as an argument to append()
:
stuff.append((name: "test 2", value: 2))
这篇关于如何将元组添加到 Swift 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!