Skip to content

Instantly share code, notes, and snippets.

@danielpi
Created April 9, 2015 22:25
Show Gist options
  • Save danielpi/43caf4f39c0322cf193b to your computer and use it in GitHub Desktop.
Save danielpi/43caf4f39c0322cf193b to your computer and use it in GitHub Desktop.
A protocol to use when you want to write a generic function that can accept Ints, Floats or Doubles.
protocol MathematicsProtocol: Equatable, Comparable, IntegerLiteralConvertible {
init(_ value: Int)
init(_ value: Float)
init(_ value: Double)
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func * (lhs: Self, rhs: Self) -> Self
func / (lhs: Self, rhs: Self) -> Self
}
extension Int: MathematicsProtocol {}
extension Float: MathematicsProtocol {}
extension Double: MathematicsProtocol {}
// Equatable means you can use ==
// Comparable means you can use < > <= >=
// IntegerLiteralConvertible means you can use integer literals
// Credit to
// http://stackoverflow.com/questions/27321763/return-int-from-a-generic-mathematics-type-in-swift
// http://stackoverflow.com/questions/25592838/generics-of-raw-types-int-float-double-create-weird-error-messages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment