0

I am trying to simplify the following repetitive code:

var cells = [Cell]()
var modules = [Module]()
var fields = [Field]()

root.child("cells").observeSingleEvent(of: .value) { (snapshot) in
    guard let dict = snapshot.value as? [String: Any],
        let cell = Cell(dict: dict) else { return }
    cells.append(cell)
}

root.child("modules").observeSingleEvent(of: .value) { (snapshot) in
    guard let dict = snapshot.value as? [String: Any],
        let module = Module(dict: dict) else { return }
    modules.append(module)
}

root.child("fields").observeSingleEvent(of: .value) { (snapshot) in
    guard let dict = snapshot.value as? [String: Any],
        let field = Field(dict: dict) else { return }
    fields.append(field)
}

Cell, Module, Field are custom struct. I am thinking whether it's possible to put their initiators init?(dict: [String: Any]) in an array and pass in dict to each of them.

1 Answer 1

1

I think you will need to make your structs adopt one protocol for that:

protocol InitializableWithDictionary {
    init?(dict: [String : Any])
}

struct Cell: InitializableWithDictionary {

    //...

    init?(dict: [String : Any]){
        //...
    }
}

struct Module: InitializableWithDictionary {

   //...

    init?(dict: [String : Any]){
       //...
    }
}

struct Field: InitializableWithDictionary {

    //...

    init?(dict: [String : Any]){
        //...
    }
}

var cells: [InitializableWithDictionary] = [Cell]()
var modules: [InitializableWithDictionary] = [Module]()
var fields: [InitializableWithDictionary] = [Field]()

root.child("cells").observeSingleEvent(of: .value) { (snapshot) in

        guard let dict = snapshot.value as? [String: Any] else { return }

        let array: [InitializableWithDictionary.Type] = [Cell.self, Module.self, Field.self]

        array.forEach {

            if let element = $0.init(dict: dict) {

                switch element {

                case is Cell: cells.append(element)
                case is Module: modules.append(element)
                case is Field: fields.append(element)
                default: break
                }

            } else { return }
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.