Last active
April 27, 2022 10:23
-
-
Save Farhandroid/c6f44b8d0029cd5965de87d2b0d81874 to your computer and use it in GitHub Desktop.
SearchGeneric
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Person: Equatable{ | |
let name: String | |
let email: String | |
let age: Int | |
} | |
func search() { | |
let henry = Person(name : "Henry", email : "[email protected]", age : 24) | |
let robert = Person(name : "Robert", email : "[email protected]", age : 22) | |
let tom = Person(name : "Tom", email : "[email protected]", age : 25) | |
let listOfPerson = Array(arrayLiteral: henry, robert, tom) | |
let searchUtil = SearchUtil(list : listOfPerson) | |
searchUtil.searchItem(element: henry) {(result) -> () in | |
print(result ?? "Not found") | |
} | |
} | |
class SearchUtil<T: Equatable>{ | |
var list: [T] = [] | |
init(list: [T]) { | |
self.list = list | |
} | |
func searchItem(element: T, foundItem: (T?)->()) { | |
let itemFoundList = self.list.filter { item in | |
item == element | |
} | |
if (itemFoundList.isEmpty){ | |
foundItem(nil) | |
} | |
else{ | |
foundItem(itemFoundList.first) | |
} | |
} | |
} | |
search() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment