Finding an Element within an Array efficiently [Swift]
Currently using the following to find a match within an array, but I want to know if there is a more efficient way of doing such a check.
for player in team.roster {
if id == player.id {
return player.name
}
}
Basically taking a variable that is given, a player id, and looping through a team roster to find a matching id, which given the size of the team is okay, but in the event a similar check is done on a larger data set what would be a better way to handle this?
Use the default property first{ condition }
let id = 4
let roster: [TeamMember] = [.init(id: 1, name: "Abishek", age: 19),
.init(id: 2, name: "Dinesh", age: 22),
.init(id: 3, name: "Praveen", age: 24),
.init(id: 4, name: "Sam", age: 25),
.init(id: 5, name: "David", age: 21)]
let firstMember = roster.first{$0.id == id}
print(firstMember)
print(firstMember?.name)
Output
Optional(TeamMember(id: 4, name: "Sam", age: 25.0))
Optional("Sam")