Sean Cook
Sean Cook

Reputation: 435

Best way to store nested data in swift

Given an object such as

objA{
  name: "A Name"
  subObj: {
    name: "A Sub Name"
  }
}

What is the best way to store this in swift? I would think to make a class of Object A and then have a value within that class that holds the subObj. But, should that subObj have its own class as well? This method seems like it would lead to an insane amount of class declaration given large data structures?

Upvotes: 0

Views: 276

Answers (1)

Sweeper
Sweeper

Reputation: 274825

IMHO, there isn't a best way for creating this kind of stuff. It depends on what you like, you data you want to store, and how deep the nesting is.

I'll show a few here.

  1. Classes and Structs

You just created some classes and/or structs that have the properties and sub-objects you want. Your example object's class might look like this

class ObjectA {
    let name: String
    let subObj: SubObject

    init(name: String, subObj: SubObject) {
        self.name = name
        self.subObj = subObj
    }
}

class SubObject {
    let name: String
    init(name: String) {
        self.name = name
    }
}

Of course, you should name your classes meaningfully.

  1. Tuples

This is best for objects which have only 1 level of nesting. You can do this with 2 but it looks kind of ugly. Don't do it with more than 3, no one understands.

This is a nested tuple:

let tuple: (String, (String, String)) = ...

If you do it with more than 3 levels of nesting, it will take people a long time to figure out what you mean:

let tuple: (String, (String, (String, (String, (String, String))))) = ...
  1. Property lists

This can be best used to store a large amount of constant data that is too verbose to create in code. Just add a new property list file into your project and read it with one of the NSBundle methods.

Your object's property list will look like this:

enter image description here

  1. JSON

Personally, I think JSON is so convenient when combined with JSON parsing libraries like SwiftyJSON. Your object's JSON representation is something like this:

objA: {
    name: "A Name",
    subObj: {
        name: "A Sub Name"
    }
}

Upvotes: 1

Related Questions