Append Dictionary type to Array in Swift

133 Views Asked by At

I am very new to Swift, I am converting my Objective-C code to Swift these days.

I declared these properties:

private var startLocation: UInt?
private var rangeIndex: UInt?
private var transaction: Array<Dictionary<String, UInt>>?
var location: UInt?

While attempting to add a Dictionary type into the transaction array, the compiler warns me.

Cannot invoke 'append' with an argument list of type '([String: UInt?])'

func beginTransaction() -> Void {
    var transaction: Dictionary = ["rangeIndex": self.rangeIndex,
                                     "location": self.location,
                                "startLocation": self.startLocation]
    self.transaction?.append(transaction) //Warn: Cannot invoke 'append' with an argument list of type '([String: UInt?])'
}
3

There are 3 best solutions below

0
On BEST ANSWER

Add !to self.rangeIndex,self.location and self.startLocation as an Implicitly Unwrapped Optional, the warning will then disappear.

func beginTransaction() -> Void {
    var transaction: Dictionary = ["rangeIndex": self.rangeIndex!,
                                     "location": self.location!,
                                "startLocation": self.startLocation!]
    self.transaction?.append(transaction)
}
0
On

This is because your array is <String, UInt> but you append <String, UInt?>

make sure they are the same.

0
On

This warning has been said very clearly: the dictionary's value inside the transaction is UInt and it can not be nil. BUT your startLocationrangeIndexlocation may be nil.