Reputation: 27
I have a dictionary of type [Int: Int] that I am trying to save to firebase. My function for writing to firebase looks like this:
func writeToFirebase() {
setScoreToBadge()
setScoreToVehicle()
if GameManager.instance.getUsername() != "" {
self.ref?.child("user").child(
GameManager.instance.getUsername()
).setValue(
[
"email": GameManager.instance.getEmail(),
"userNameLowered": GameManager.instance.getUsername().lowercased(),
"userName": GameManager.instance.getUsername(),
"topScore": GameManager.instance.getTopScores()[0],
"topScores": GameManager.instance.getTopScores(),
"totalCash": GameManager.instance.getTotalCash(),
"friends": GameManager.instance.getFriendsAdded(),
"achievements": GameManager.instance.getAchievementsCompletedBool(),
"badge": GameManager.instance.getBadgeLevel(),
"scoreBadgeDictionary" : GameManager.instance.getTopScoreWithBadgeDictionary(),
"scoreVehicleDictionary" : GameManager.instance.getTopScoreWithVehicleDictionary()
])
} else {
print ("Not signed in, score not saved to firebase")
}
}
The issue I'm having is with scoreBadgeDictionary
and , scoreVehiceDictionary
. GameManager.instance.getTopScoreWithBadgeDictionary()
is a dictionary of type [Int: Int]
and GameManager.instance.getTopScoreWithVehicleDictionary()
is a dictionary of type [Int: String]
. If I try to run this function it will crash.
Is there a way to convert the dictionary to a format that I can save to firebase?
Upvotes: 0
Views: 957
Reputation: 35648
This issue is how the array is defined. A simple example
let myArray = ["some_key": "some_value"]
is defined as an array of [String: String]
and
let myArray = ["some_key": 5]
is defined as an array of [String: Int]
Your array is
[
"email": GameManager.instance.getEmail(),
"userNameLowered": GameManager.instance.getUsername().lowercased(),
.
.
"scoreBadgeDictionary" : ["some key": "some value"]
]
where, I assume GameManager.instance.getTopScoreWithBadgeDictionary() returns a dictionary.
So that array doesn't conform to [String: String] or [String: Int]. However it does conform to a more generic [String: Any] so that's what you need to 'tell' the var.
let myArray: [String: Any] = [
"email": "Hello",
"userNameLowered": "hello",
"scoreBadgeDictionary" : [1: "some score"],
"scoreVehicleDictionary" : [2: "some vehicle"]
]
However, and this is the important bit, the dictionaries returned in getTopScoreWithVehicleDictionary
which is a [Int: String] or [Int: Int] is not going to work with Firebase.
Firebase keys must be strings so attempting to write this [1: "Hello, World] will crash. Noting that arrays in Firebase have numeric indexes and
if the data looks like an array, Firebase will render it as an array.
I would suggest rethinking that structure - possibly cast the Int's to a string would be an option but that may not work for your use case.
Upvotes: 1