Skip to content

Instantly share code, notes, and snippets.

@jerryhjones
Last active August 29, 2015 14:02
Show Gist options
  • Save jerryhjones/cc9437d3103c26cb46fd to your computer and use it in GitHub Desktop.
Save jerryhjones/cc9437d3103c26cb46fd to your computer and use it in GitHub Desktop.
//
// SwiftMath.swift
// SMPageControlFramework
//
// Created by Jerry Jones on 6/7/14.
// Copyright (c) 2014 Spaceman Labs, Inc. All rights reserved.
//
import Foundation
protocol Floorable : FloatingPointNumber {
var floored: Self { get }
}
extension Float : Floorable {
var floored: Float {
get {
return floorf(self)
}
}
}
extension Double : Floorable {
var floored: Double {
get {
return floor(self)
}
}
}
protocol Ceilable : FloatingPointNumber {
var ceiled: Self { get }
}
extension Float : Ceilable {
var ceiled: Float {
get {
return ceilf(self)
}
}
}
extension Double : Ceilable {
var ceiled: Double {
get {
return ceil(self)
}
}
}
func floor<T: Floorable>(item: T) -> T
{
return item.floored
}
func ceil<T: Ceilable>(item: T) -> T
{
return item.ceiled
}
//Lets me do this
var foo: Float = 10.51212121
var bar: Double = 10.51212121
foo.floored
bar.floored
floor(foo)
floor(bar)
foo.ceiled
bar.ceiled
ceil(foo)
ceil(bar)
@n8gray
Copy link

n8gray commented Jun 8, 2014

I worry that dispatching floor through a protocol might hurt performance -- it potentially requires a protocol-specific dispatch table for each type that implements the protocol. I know it's kind of silly, but for basic floating point math ops I would be cautious about that. My idea was to use function overloading to add floor to Float, since the compiler has to choose the right function at compile time and can hopefully inline it:

func floor(f:Float) -> Float { return floorf(f) }

floor(foo)  // Hits our overload
floor(bar)  // Hits the system floor()

The .floored methods are probably fine -- I'm guessing the compiler can optimize those pretty well.

Caveat: I don't actually know anything about Swift performance. 😆

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment