liveBook · Manning

Summable

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

A book-specific Swift protocol for types whose instances can be combined with the + operator.

Summable is a Swift protocol for types whose instances can be combined with the + operator. It lets weighted graph types accept generic weights while requiring addition; weights must also be Comparable for graph algorithms that select the smallest edge. section 4.3

public protocol Summable {
    static func +(lhs: Self, rhs: Self) -> Self
}

The protocol declares one requirement: a static + operator that combines two values of the same type. section 4.3

Using numeric weights

Swift’s numeric types already implement +, so they can receive Summable conformance through extensions such as extension Int: Summable {}. A generic WeightedGraph<String, Int> can then store city-to-city distances and add edge weights when computing a total. section 4.3

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines the protocol signature and numeric conformances, then applies the constraint in weighted graph and total-weight code.
Examples
Uses Int, Double, and Float conformances, city-distance weights, and a totalWeight reduction over weighted edges.
What it assumes
Assumes familiarity with Swift protocols, generics, operator overloading, and Comparable.
What you can do after
Build it from scratch by defining a + requirement and constraining generic weighted graph types with Summable.
How it connects
Connects operator overloading, Comparable, generics, weighted graphs, and minimum spanning trees.

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.