I'm trying to factorize methods using generics in Swift. My methods are as follow:
func searchFoo(searchText: String?, completion: @escaping ([Foo]?, Error?) -> ()) {
let index = "foo" // <- How can I assign this from a generic type?
searchClient.search(index, searchText) { (json, error) in
if let json = json {
completion(self.fooFrom(json: json), nil)
} else if let error = error {
completion(nil, error)
} else {
completion([], nil)
}
}
}
func searchBar(searchText: String?, completion: @escaping ([Bar]?, Error?) -> ()) {
let index = "bar" // <- How can I assign this from a generic type?
searchClient.search(index, searchText) { (json, error) in
if let json = json {
completion(self.barFrom(json: json), nil)
} else if let error = error {
completion(nil, error)
} else {
completion([], nil)
}
}
}
These 2 functions look like a good usecase for generics but I can't figure out how I could switch on a generic type to get the 2 required strings.
Of course, I could put the index name in the function signature, but I feel that it would be redundant as the index name is implied by the generic type actually being used and it could be a source of bugs.
I feel like I'm missing something as I may not think the Swift way yet, so any help would be welcome to get a good refactoring for this code.