Last active
August 29, 2015 14:26
-
-
Save Istar-Eldritch/3e48562b30e1a5d12d9b 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
// | |
// Number.swift | |
// | |
// This allows the use of the Type Number in Generics | |
// Allow operations between optional numbers. | |
// | |
// Created by Ruben Paz | |
// | |
import Foundation | |
protocol Number { | |
func +(lhs: Self, rhs: Self) -> Self | |
func -(lhs: Self, rhs: Self) -> Self | |
func *(lhs: Self, rhs: Self) -> Self | |
func /(lhs: Self, rhs: Self) -> Self | |
func %(lhs: Self, rhs: Self) -> Self | |
init(_ v: Int) | |
} | |
extension Double : Number {} | |
extension Float : Number {} | |
extension Int : Number {} | |
extension Int8 : Number {} | |
extension Int16 : Number {} | |
extension Int32 : Number {} | |
extension Int64 : Number {} | |
extension UInt : Number {} | |
extension UInt8 : Number {} | |
extension UInt16 : Number {} | |
extension UInt32 : Number {} | |
extension UInt64 : Number {} | |
func optionalOperation <T: Number>(n1:Optional<T>, n2:Optional<T>, operation: (T, T) -> T) -> Optional<T> { | |
if n1 != nil && n2 != nil { | |
return operation(n1!, n2!) | |
} | |
else { | |
return nil | |
} | |
} | |
func - <T: Number>(n1:Optional<T>, n2:Optional<T>) -> Optional<T> { | |
return optionalOperation(n1, n2, {$0 - $1}) | |
} | |
func + <T: Number>(n1:Optional<T>, n2:Optional<T>) -> Optional<T> { | |
return optionalOperation(n1, n2, {$0 + $1}) | |
} | |
func * <T: Number>(n1:Optional<T>, n2:Optional<T>) -> Optional<T> { | |
return optionalOperation(n1, n2, {$0 * $1}) | |
} | |
func / <T: Number>(n1:Optional<T>, n2:Optional<T>) -> Optional<T> { | |
return optionalOperation(n1, n2, {$0 / $1}) | |
} | |
func % <T: Number>(n1:Optional<T>, n2:Optional<T>) -> Optional<T> { | |
return optionalOperation(n1, n2, {$0 % $1}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment