Where Clause Constraint in Swift

Level 5664 keystrokes

where clauses add constraints to generic parameters. findLatest requires T to conform to both Identifiable and Timestamped and returns the element with the largest timestamp, printing Latest: End at 200.

Swift code

// Two small protocols, each with one property requirement
1protocol Identifiable {
2 var id: String { get }
3}
4
5protocol Timestamped {
6 var timestamp: Int { get }
7}
8
// Event conforms to both protocols
9struct Event: Identifiable, Timestamped {
10 var id: String
11 var timestamp: Int
12 var name: String
13}
14
// where T: Identifiable & Timestamped requires both protocols
15func findLatest<T>(_ items: [T]) -> T? where T: Identifiable & Timestamped {
// max(by:) returns the element with the largest timestamp (nil if empty)
16 return items.max(by: { $0.timestamp < $1.timestamp })
17}
18
// Mixes an inline constraint with a where clause; never called (Event is not Equatable)
19func findById<T: Identifiable>(_ items: [T], id: String) -> T? where T: Equatable {
// Returns the first element with a matching id
20 return items.first(where: { $0.id == id })
21}
22
23let events = [
24 Event(id: "1", timestamp: 100, name: "Start"),
25 Event(id: "2", timestamp: 200, name: "End")
26]
// The result is optional, so it is unwrapped with if let
27if let latest = findLatest(events) {
// Prints Latest: End at 200
28 print("Latest: \(latest.name) at \(latest.timestamp)")
29}

Output

Latest: End at 200
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • :× 21
  • "× 10
  • (× 10
  • )× 10
  • {× 10
  • }× 10
  • ,× 7
  • .× 7
  • =× 4
  • >× 4

More Swift examples at level 5

← Swift typing practice