Carmelo Carmelo - 6 months ago 9
Swift Question

Add element to a complex nested collection in swift

I'm stuck practicing collections in Swift. Actually, I storing data from an online JSON source into dictionaries/arrays. I'm trying to add a new element to the following collection:

testDict1: Dictionary<String,Dictionary<Int,Dictionary<String, AnyObject>>>


I initialized it with the following elements (it could have been an empty array):

testDict1 = ["fireMagic":[
0:["name":"Basic attack","damage":100],
1:["name":"Super attack","damage":200, "lvlReq": 20],
2:["name":"Mega attack","damage":400, "lvlReq": 40]]]


I would like to "update" data within testDict1 (replace and add a new row if needed) from another array such as:

testDict1 = ["fireMagic":[
0:["name":"Basic attack","damage":100],
1:["name":"Super attack","damage":200, "lvlReq": 20],
2:["name":"Mega attack","damage":400, "lvlReq": 40]
3:["name":"Insane attack","damage":1000, "lvlReq": 60]]]


QUESTION 1

How can I append the element below to testDict1:

3:["name":"Insane attack","damage":1000, "lvlReq": 60] //with "FireMagic" as a key.


I'm facing different errors and I can't make it work. I'm sure it must be more complex than the ways I tried and you may have the solution to end my pain :)

QUESTION 2

How do I do if I need to add other powers such as "WaterMagic" with the same structure as "FireMagic" in testDict1.

testDict1 = ["fireMagic":[
0:["name":"Basic attack","damage":100],
1:["...":"...","...":"..."]],
["waterMagic":[
0:["name":"Basic attack","damage":100]]


Thank you in advance for your help in my learning quest!

Answer

Q1:

Unsafe:

testDict1["fireMagic"]![3] = ["name":"Insane attack","damage":1000, "lvlReq": 60]

Safe:

if let _ = testDict1["fireMagic"] {
    testDict1["fireMagic"]![3] = ["name":"Insane attack","damage":1000, "lvlReq": 60]
}

Safe and simple (thanks @dfri):

testDict1["fireMagic"]?[3] = ["name":"Insane attack","damage":1000, "lvlReq": 60]

Q2:

testDict1["waterMagic"] = [0:["name":"Test attack","damage":100]]

But I would suggest using arrays, enums and structs instead of dictionaries, it's much simpler to handle, and it's also more safe:

enum MagicType {
    case Water
    case Fire
}

struct Magic {
    let magic: MagicType
    let name: String
    let damage: Int
    let lvlReq: Int?
}

Create an array of objects:

var fireMagics = [Magic(magic: .Fire, name: "Basic attack", damage: 100, lvlReq: nil), Magic(magic: .Fire, name: "Super attack", damage: 200, lvlReq: 20), Magic(magic: .Fire, name: "Mega attack", damage: 100, lvlReq: 40)]

Access the objects in the array by index:

fireMagics[0]
fireMagics[1]
fireMagics[2]

etc.

Add an object to the array:

fireMagics.append(Magic(magic: .Fire, name: "Insane attack", damage: 1000, lvlReq: 60))

Create a different type of Magic object:

var waterMagics = [Magic(magic: .Water, name: "Test attack", damage: 100, lvlReq: nil)]
Comments