Zigii Wong Zigii Wong - 1 month ago 8
Swift Question

Append Dictionary type to Array in Swift

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?])'
}

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)
}
Comments