How to append a tuple to an array object in Swift code?
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"))
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.
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.
How do I add a tuple to a Swift Array?
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)]
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))
Accessing an array of tuples Swift 4
You should do something like this:
class eventCell: UICollectionViewCell {
@IBOutlet private weak var eventTitle: UILabel!
@IBOutlet private weak var descriptionLabel:UILabel!
@IBOutlet private weak var eventImage: UIImageView!
typealias Event = (title:String, location:String, lat:CLLocationDegrees, long:CLLocationDegrees)
var eventArray = [Event]()
override func prepareForReuse() {
eventImage.image = nil
}
func lool() {
var event = Event(title: "a", location:"b", lat:5, long:4)
eventArray.append(event)
eventTitle.text = eventArray[0].title
}
}
Tuple containing an array (and assigned as variable) not working?
This should work:
let arrayOfObjects : [myObject] = []
tuples.append(letter:"t", objects: arrayOfObjects)
As you can see, arrayOfObjects
is a constant. The problem here might stem from the fact that append
expects a constant parameter T
, while you are passing a tuple containing a var
.
IMHO this is what makes append
goes a little crazy, and the compiler gives a crazier error description ;-)
Understanding syntax for an array of tuples in Swift
The Swift type inference system is being stretched to the point of breaking here. Swift is having trouble inferring the type of [(1600, "Maggie")]
in your example. If you give it a little more information, your example will compile:
gameScores += [(1600, "Maggie") as (points: Int, player: String)]
gameScores += [(1600, "Maggie")] as [(points: Int, player: String)]
and
gameScores = gameScores + [(1600, "Maggie")]
all compile.
It seems Swift is having trouble inferring the type when +=
is involved.
Looking at the definition of +=
:
func +=<C : Collection>(lhs: inout Array<C.Iterator.Element>, rhs: C)
shows that the types of the lhs
and rhs
are different. Swift is having trouble reconciling the types of the lhs
and the rhs
from the information given. It seems to be starting with the rhs
and then concludes that the type of the lefthand side is inout _
and it tries to reconcile that with the type of gameScores
which is [(points: Int, player: String)]
. Should it be able to infer the types? Perhaps, but in this case, since you have an easy workaround, I say give the compiler a break and give it the explicit type information and make its job easier:
gameScores += [(points: 1600, player: "Maggie")]
update an array of tuples with certain index
It's not a multidimensional array but array of tuples with named parameters. Try:
rowContent[1].description = descriptionTranferred
But I'm guessing that you're trying to change description in tuple on index that matches identifier so replace your if
condition:
if let index = rowContent.index(where: {$0.title == identifier}) {
rowContent[index].description = descriptionTranferred
}else {
print ("nothing")
}
How do I create an array of tuples?
It works with a type alias:
typealias mytuple = (num1: Int, num2: Int)
var fun: mytuple[] = mytuple[]()
// Or just: var fun = mytuple[]()
fun.append((1,2))
fun.append((3,4))
println(fun)
// [(1, 2), (3, 4)]
Update: As of Xcode 6 Beta 3, the array syntax has changed:
var fun: [mytuple] = [mytuple]()
// Or just: var fun = [mytuple]()
How do I create an array of tuples in Swift where one of the items in the tuple is optional?
This could be a compiler bug. As in How do I create an array of tuples?,
you can define a type alias as a workaround:
typealias NameTuple = (firstName: String, middleName: String?)
var tupleArray: [NameTuple] = []
tupleArray.append( (firstName: "Bob", middleName: nil) )
tupleArray.append( (firstName: "Tom", middleName: "Smith") )
Swift: Get an array of element from an array of tuples
That's simple:
answers.map { $0.number }
Related Topics
Setting the Timelineprovider Refresh Interval For Widget
Nsfontattributedstring Worked Before Xcode 6.1
Swift Cross Compile to Single Linux Binary
Change the Value That Is Being Set in Variable's Willset Block
Swift Alternative to Performselectoronmainthread
Multiple Type Constraints in Swift
How to Create Custom Notifications in Swift 3
How to Create a Fixed-Size Array of Objects
What Are the Differences Between Throws and Rethrows in Swift
Dismiss Keyboard with a Uitextview
Swiftui - Passing Data from Swiftuiview to Scenekit
How to Transpose an Array More Swiftly
Swift 2 to 3 Migration for Prepareforsegue
Convert a Swift Array of String to a to a C String Array Pointer
How to Load an Image from Documents Directory on MACos Swift