Carl Carl - 2 days ago 5
Swift Question

where to put code that operates on an array of structs?

If I have a struct and some code that processes arrays of this struct, where would be the place to put this code?

struct Thing {
var id : String
let type : ThingType
}

things:[Thing]?


I have code to retrieve values from a server which returns an array of
100 Thing
. Where should the code go?

I've currently defined it as a static function of the Struct but would like to follow a convention, if there is one.

Answer

A function that retrieves Thing instances from a server most certainly should not be a member of Thing.

It's best to make a new protocol that declares the function, like so:

protocol ThingProvider {
    func fetchThings() -> [Thing]
}

and a conforming type:

class DataBaseThingProvider: ThingProvider {

    init() {
        // open database connection
    }

    deinit() {
        // close database connection
    }

    func fetchThings() -> [Thing] {
        // fetch Things from database
    }
}

This way, you can change the provider you use (Firebase, Parse, SQLite, CoreData, JSON, CSV, whatever.) by just swapping out the concrete provider class you use, and all other code can stay the same.

It also makes your code much more testable, because you can easily construct a mock provider, which decouples your tests from your production backend.

class MockThingProvider: ThingProvider {

    func fetchThings() -> [Thing] {
        return [
            Thing(id: "MockThing1", type: thingType1),
            Thing(id: "MockThing2", type: thingType2),
            Thing(id: "MockThing3", type: thingType3)
        ]
    }
}
Comments