Home > Software design >  SWIFT "3 levels array"
SWIFT "3 levels array"

Time:01-11

I have a little problem with using arrays and declaring it in swift 5 on OSX:

  • I know an [[String]] is an array of arrays like [["team1", "2 goals"], ["team2", "0 goals"]]. Well it's easy for my, but let me explain my case:

  • I have an array of "Systems", which is like -> ["nes", "Xbox" , "ps2"]

  • every "System" have "Games" and every "game" in "Games" have an array of properties like "name", "thumbnail", "video", etc...

I need to create an array like ->

["xbox" , [["game1",array of properties],["game2", array of properties]]]

I tried to define an [[[String]]]

var allMyGames = [[[String]]]()

but I don´t know how to myGames.append this...

I have an array named myGames = [[String]]() which contains data like ["game1", "property1", "property2" ,"property3"] ["game2", "property1", "property2" ,"property3"]

and another array with the systems mySystems = [String]() my contains data like ["nes", "xbox", "ps2"]

Any idea?

thanks in advance

CodePudding user response:

You would be much better modelling your problem using structs. Here is a start for you to show how you might start modelling your problem.

OK, let's start by creating a game with a name, thumbnail image and video.

struct Game {
  let name: String
  let thumbnailURL: URL
  let videoURL: URL
}

Now we can create a system...

struct System {
  let name: String
  let games: [Game]
}

And now you can create your array of systems...

let systems = [
  System(
    name: "Xbox",
    games: [
      Game(name: "Halo", thumbnailURL: ... videoURL: ...),
    ]
  ),
  System(
    name: "NES",
    games: [
      Game(name: "Super Mario Bros", thumbnailURL: ... videoURL: ...),
    ]
  )
]

As you can see you end up with a much easier way to model the different systems and games etc...

  •  Tags:  
  • Related