且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Swift 代码中将元组附加到数组对象?

更新时间:2022-03-25 15:51:13

只需将元组分配给临时变量即可:

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.