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 requirement1protocol Identifiable {2 var id: String { get }3}4 5protocol Timestamped {6 var timestamp: Int { get }7}8 // Event conforms to both protocols9struct Event: Identifiable, Timestamped {10 var id: String11 var timestamp: Int12 var name: String13}14 // where T: Identifiable & Timestamped requires both protocols15func 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 id20 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 let27if let latest = findLatest(events) { // Prints Latest: End at 20028 print("Latest: \(latest.name) at \(latest.timestamp)")29}Output
Latest: End at 200
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