How do I add a tuple to a Swift Array?

后端 未结 8 504
夕颜
夕颜 2021-01-30 03:02

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 g

8条回答
  •  梦谈多话
    2021-01-30 03:53

    You have two issues. First problem, you're not creating an "array of tuples", you're creating an "optional array of tuples". To fix that, change this line:

    var myStringArray: (String,Int)[]? = nil
    

    to:

    var myStringArray: (String,Int)[]
    

    Second, you're creating a variable, but not giving it a value. You have to create a new array and assign it to the variable. To fix that, add this line after the first one:

    myStringArray = []
    

    ...or you can just change the first line to this:

    var myStringArray: (String,Int)[] = []
    

    After that, this line works fine and you don't have to worry about overloading operators or other craziness. You're done!

    myStringArray += ("One", 1)
    

    Here's the complete solution. A whopping two lines and one wasn't even changed:

    var myStringArray: (String,Int)[] = []
    myStringArray += ("One", 1)
    

提交回复
热议问题