Zigii Wong
Zigii Wong

Reputation: 7826

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

Upvotes: 1

Views: 113

Answers (3)

Zigii Wong
Zigii Wong

Reputation: 7826

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

Upvotes: 1

Bannings
Bannings

Reputation: 10479

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.

Upvotes: 1

JZAU
JZAU

Reputation: 3567

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

make sure they are the same.

Upvotes: 1

Related Questions