如何在 Swift 代码中将元组附加到数组对象? [英] How to append a tuple to an array object in Swift code?
问题描述
我搜索了谷歌,但我找不到在 Swift 中将新元素附加到数组对象的方法.出现错误代码在调用中缺少参数名称"的参数".遵循我的代码.
I searched google, but i cant find a way to append new element to array object in Swift. The error code "Missing arguments fot parameter "name" in call" is come up. My code is followed.
var arrayObj: [(id: Int, name: String)] = []
var idInt: Int = 1
var nameString: String = "hoge"
arrayObj.append(( // ----> "Missing arguments fot parameter "name" in call"
id: idInt,
name: nameString
))
如果您知道任何解决方案,我会很高兴.谢谢.
if you know any solution, I'd be very glad. Thanks.
推荐答案
只需将元组分配给临时变量即可:
Just assign the tuple to a temp variable:
let tuple = (
id: idInt,
name: nameString
)
arrayObj.append(tuple)
不知道为什么它不能那样工作 - 只是检查了一个函数,如下所示:
Not sure why it doesn't work that way - just checked on a function, like this:
var array: [(param1: Int, param2: String)] = []
func test(x: (param1: Int, param2: String)) {
println(x)
}
test((param1: 2, param2: "Test"))
array.append((param1: 2, param2: "Test"))
结果:函数有效,数组方法无效.
Result: the function works, the array method doesn't.
更新:在操场上试过这个代码:
Update: Tried this code in a playground:
struct Test<T> {
func doSomething(param: T) {
println(param)
}
}
var test = Test<(param1: Int, param2: String)>()
let tuple = (param1: 2, param2: "Test")
test.doSomething(tuple)
test.doSomething((param1: 2, param2: "Test"))
结果:它在将 tuple
变量传递给 doSomething
时起作用 - 尽管编译器消息不同,但使用文字元组却不起作用:
Result: it works when passing the tuple
variable to doSomething
- using the literal tuple instead doesn't, although the compiler message is different:
'((param1: Int, param2: String)) ->()' does not have a member named 'doSomething'
显然编译器没有正确处理将文字元组传递给泛型类的方法(其中元组是泛型类型).
Apparently passing a literal tuple to a method of a generic class (where the tuple is the generic type) is not correctly handled by the compiler.
更新 #2:我在非泛型类上重复了测试,但使用了泛型方法,在这种情况下它有效:
Update #2: I repeated the test on a non-generic class, but using a generic method, and in this case it worked:
struct Test {
func doSomething<T>(param: T) {
println(param)
}
}
var test = Test()
let tuple = (param1: 2, param2: "Test")
test.doSomething(tuple)
test.doSomething((param1: 2, param2: "Test"))
所以这绝对是一个与泛型类相关的问题.
So it's definitely a problem related to generic classes only.
这篇关于如何在 Swift 代码中将元组附加到数组对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!