Reputation: 5340
Is there a particular reason why Apple defined CGFloat.zero
? When should we use it? And how is it different from 0
?
Upvotes: 3
Views: 1450
Reputation: 299265
Generic algorithms are built on top of protocols which let us write common code that can apply to many types. The AdditiveArithmetic protocol requires that conforming types have a zero value (.zero
) which can be used for algorithms that require that. With that, you can write a single function that can work with the many different kinds of integers (Int16, Int32, Int…), floats (Double, Float, CGFloat…), and even vectors. Anything that has an arithmetic zero, the concept of "adding and subtracting," and can be equated (since AdditiveArithmetic requires Equatable), can participate.
AdditiveArithmetic does not require that a type conform to ExpressibleByIntegerLiteral, which means that it may not be possible create the type using the 0
symbol. Vector types typically are not initialized this way, but still have a "zero value."
As an example of how you can use this, consider sum()
, which can work on integers, floats, vectors, or any custom type you would like to make that conforms to AdditiveArithmetic:
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
reduce(.zero, +)
}
}
Upvotes: 9