Swift generics: It's all in the protocols (Part I)


To begin writing a generic function, first of all you need to decide on the range of types that you'd like to invite to your party. And since we want to be as inclusive as possible, why not go crazy and invite all the members of Hashable?
struct Bool
struct CFunctionPointer
struct COpaquePointer
struct Double
struct Float
struct Float80
struct Int
struct Int8
struct Int16
struct Int32
struct Int64
struct ObjectIdentifier
struct String
struct UInt
struct UInt8
struct UInt16
struct UInt32
struct UInt64
struct UnicodeScalar
struct UnsafePointer
Problem is, once they're inside the party there's very little we can do to entertain them:
func ha<T: Hashable>(t:T, b:T) {
    t.hashValue
    t == b
}
This is because Hashable only requires that adoptees employ the hashValue property, and Equatable (the only protocol that Hashable adopts) only requires == to be employed.

Your name's not down...

If we choose something a bit more exclusive, like FloatingPointType then our range of properties and methods broaden:
func fl<T:FloatingPointType>(t:T,b:T) {
    
    // FloatingPointType
    t._toBitPattern()
    t.isFinite
    t.isFinite
    t.isNaN
    t.isNormal
    t.isSignaling
    t.isSignMinus
    t.isSubnormal
    t.isZero
    
    // Strideable
    t.distanceTo(b)
    t.advancedBy(2)
    
    // Comparable
    t <= b
    t >= b
    t > b
    t < b
    
    // Equatable
    t == b
}
But now we are confined to only two Types:
struct Double
struct Float
It's a rather quiet party with lots to do. Double and Float have the bouncy castle all to themselves!

Endorse on Coderwall

Comments