typestar

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

  1. <T: Comparable> accepts any self-comparable type.
  2. The same fastest ranks Doubles and Strings.
  3. middle returns T? — empty arrays have no middle.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Abstractions, step 21 of 27 in Language basics.

← Previous Next →

Generics in other languages