我正在尝试简化以下重复代码:
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
是自定义结构。我在想是否可以将他们的启动器init?(dict: [String: Any])
放在一个数组中并将dict
传递给它们中的每一个。
答案 0 :(得分:1)
我认为你需要让你的结构采用一个协议:
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 }
}
}