Search a list of records: Difference between revisions

Content added Content deleted
(Add Swift)
Line 2,496: Line 2,496:
val firstBelow5M = "Khartoum-Omdurman" : string
val firstBelow5M = "Khartoum-Omdurman" : string
val firstPopA = 4.58 : real</pre>
val firstPopA = 4.58 : real</pre>

=={{header|Swift}}==

Data:

<lang swift>struct Place {
var name: String
var population: Double
}

let places = [
Place(name: "Lagos", population: 21.0),
Place(name: "Cairo", population: 15.2),
Place(name: "Kinshasa-Brazzaville", population: 11.3),
Place(name: "Greater Johannesburg", population: 7.55),
Place(name: "Mogadishu", population: 5.85),
Place(name: "Khartoum-Omdurman", population: 4.98),
Place(name: "Dar Es Salaam", population: 4.7),
Place(name: "Alexandria", population: 4.58),
Place(name: "Abidjan", population: 4.4),
Place(name: "Casablanca", population: 3.98)
]</lang>

===Using built-in methods===

<lang swift>guard let salaamI = places.firstIndex(where: { $0.name == "Dar Es Salaam" }) else {
fatalError()
}

print("Dar Es Salaam has index: \(salaamI)")

guard let lessThan5 = places.first(where: { $0.population < 5 }) else {
fatalError()
}

print("First city with less than 5mil population: \(lessThan5.name)")

guard let startsWithA = places.first(where: { $0.name.hasPrefix("A") }) else {
fatalError()
}

print("Population of first city starting with A: \(startsWithA.population)")</lang>

{{out}}

<pre>Dar Es Salaam has index: 6
First city with less than 5mil population: Khartoum-Omdurman
Population of first city starting with A: 4.58</pre>

===Custom method using Key Paths===

<lang swift>extension Collection {
func firstIndex<V: Equatable>(
withProperty prop: KeyPath<Element, V>,
_ op: (V, V) -> Bool,
_ val: V
) -> Index? {
for i in indices where op(self[i][keyPath: prop], val) {
return i
}

return nil
}
}

guard let salaamI = places.firstIndex(withProperty: \.name, ==, "Dar Es Salaam") else {
fatalError()
}

print("Dar Es Salaam has index: \(salaamI)")

guard let lessThan5I = places.firstIndex(withProperty: \.population, <, 5) else {
fatalError()
}

print("First city with less than 5mil population: \(places[lessThan5I].name)")

guard let aI = places.firstIndex(withProperty: \.name, { $0.hasPrefix($1) }, "A") else {
fatalError()
}

print("Population of first city starting with A: \(places[aI].population)")</lang>

{{out}}

Same as first method


=={{header|Tcl}}==
=={{header|Tcl}}==