@Shabnam Siddiqui answer is Swifty and I would use it most of the time, but the binary search is worth to know as well.
The Swift method first(where:) in O(n)complexity
https://developer.apple.com/documentation/swift/array/1848165-first, whereas a binary search has a worst-case performance of O(log n) and a best-case performance of O(1).
So assuming :
struct Player {
var id : Int
var name : String
}
for :
var players : [Player] = [
Player(id: 0, name: "Bob"),
Player(id: 1, name: "Edd"),
Player(id: 2, name: "Jo"),
Player(id: 3, name: "John")
]
Solution recursive :
func getPlayername(_ id : Int, _ players : [Player]) -> String?{
guard players.count > 0 else {
print("No players found with id \(id)")
return nil
}
if players.first!.id == id {
return players.first?.name
}else{
return getPlayername(id, Array(players.dropFirst()))
}
}
print(getPlayername(3, players))
Solution binary :
func getPlayerBinary(_ id : Int, _ players : [Player]) -> String?{
var startIndex = 0
var max = players.count
while startIndex < max {
let midIndex = startIndex + (max - startIndex) / 2
if players[midIndex].id == id {
return players[midIndex].name
} else if players[midIndex].id < id {
lowerBound = midIndex + 1
} else {
max = midIndex
}
}
print("No players found with id \(id)")
return nil
}
https://www.geeksforgeeks.org/binary-search/