Generic Type Constraint in Swift

Level 5357 keystrokes

The Summable protocol requires + and a zero value. Int and Double are made to conform, and sum<T: Summable> adds the elements of any such array starting from T.zero, printing 15 and 7.0.

Swift code

1protocol Summable {
// Requires a + operator; Self is the conforming type
2 static func +(lhs: Self, rhs: Self) -> Self
// Requires a static zero, used as the starting value
3 static var zero: Self { get }
4}
5
// Int already has +, so only zero needs to be added
6extension Int: Summable { static var zero: Int { 0 } }
// The same for Double
7extension Double: Summable { static var zero: Double { 0.0 } }
8
// T: Summable restricts T to types that conform to Summable
9func sum<T: Summable>(_ items: [T]) -> T {
// The constraint guarantees T.zero and + exist
10 return items.reduce(T.zero) { $0 + $1 }
11}
12
// T is Int: prints 15
13print(sum([1, 2, 3, 4, 5]))
// T is Double: prints 7.0
14print(sum([1.5, 2.5, 3.0]))

Output

15
7.0
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.

  • :× 9
  • {× 8
  • }× 8
  • ,× 7
  • (× 7
  • )× 7
  • .× 6
  • [× 3
  • ]× 3
  • >× 3

More Swift examples at level 5

← Swift typing practice