Skip to content

Instantly share code, notes, and snippets.

@SteveRohrlack
Created September 13, 2016 07:58
Show Gist options
  • Save SteveRohrlack/4042950f21517a0a549aaff67fca71f5 to your computer and use it in GitHub Desktop.
Save SteveRohrlack/4042950f21517a0a549aaff67fca71f5 to your computer and use it in GitHub Desktop.
Swift 2.2 example showing how a generic protocol can be "Equatable"
import Foundation
/**
generic protocol that is Equatable by itself
and wraps any equatable data type
*/
protocol SameOldThingable: Equatable {
associatedtype DataType: Equatable
var data: DataType { get set }
}
/**
"equals" operator overloading
this makes SameOldThingable Equatable
- parameter lhs: SameOldThingable
- parameter rhs: SameOldThingable
- return: Bool
*/
func ==<T: SameOldThingable>(lhs: T, rhs: T) -> Bool {
return lhs.data == rhs.data
}
/**
concrete type that adopts "SameOldThingable"
this is implemented using generics but "SameOldThing" could also use a
typealias to specify what concrete type the associated type "DataType"
of the "SameOldThingable" protocol should be
*/
struct SameOldThing<DataType: Equatable>: SameOldThingable {
var data: DataType
}
// MARK: demo
let hello = SameOldThing<String>(data: "Hello")
let world = SameOldThing<String>(data: "World")
// not equal
assert((hello == world) == false)
let anotherHello = SameOldThing<String>(data: "Hello")
// equal
assert((hello == anotherHello) == true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment