Last active
August 29, 2015 14:02
-
-
Save jerryhjones/cc9437d3103c26cb46fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 addfloor
to Float, since the compiler has to choose the right function at compile time and can hopefully inline it: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. 😆