Generics in Swift
Type parameters at the call site, bounded where needed.
// T is chosen at the call site; the constraint keeps it comparable.
func fastest<T: Comparable>(_ a: T, _ b: T) -> T {
a < b ? a : b
}
func middle<T>(_ items: [T]) -> T? {
items.isEmpty ? nil : items[items.count / 2]
}
print(fastest(3612.0, 3599.5))
print(fastest("Kestrel", "Brant"))
let order = ["pin", "windward", "leeward", "finish"]
print("Halfway mark: \(middle(order) ?? "none")")
print("Empty course: \(middle([Int]()) ?? -1)")
How it works
<T: Comparable>accepts any self-comparable type.- The same
fastestranks Doubles and Strings. middlereturnsT?— empty arrays have no middle.
Keywords and builtins used here
ComparableIntcountfastestfuncisEmptyletmiddleprint
The run, in numbers
- Lines
- 15
- Characters to type
- 439
- Tokens
- 142
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 131 seconds.
Step 3 of 3 in Abstractions, step 21 of 27 in Language basics.