Created
August 28, 2015 08:14
-
-
Save hiroshi-maybe/fc31a02d3d3e4658c929 to your computer and use it in GitHub Desktop.
example of protocol extension
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
| //: Playground - noun: a place where people can play | |
| import UIKit | |
| var str = "Hello, playground" | |
| /* | |
| class (Eq a, Show a) => Num a where | |
| (+) :: a -> a -> a | |
| (-) :: a -> a -> a | |
| (*) :: a -> a -> a | |
| negate :: a -> a | |
| abs :: a -> a | |
| signum :: a -> a | |
| fromInteger :: Integer -> a | |
| fromInt :: Int -> a | |
| */ | |
| protocol Num: CustomStringConvertible, Equatable { | |
| func +(left: Self, right: Self) -> Self | |
| func -(left: Self, right: Self) -> Self | |
| func *(left: Self, right: Self) -> Self | |
| var isNegative: Bool { get } | |
| var negate: Self { get } | |
| var abs: Self { get } | |
| static func fromInt(intValue: Int) -> Self | |
| } | |
| extension Num { | |
| var negate: Self { | |
| return isNegative ? self : Self.fromInt(-1) * self | |
| } | |
| var abs: Self { | |
| return !isNegative ? self : Self.fromInt(-1) * self | |
| } | |
| } | |
| /* | |
| instance Num Int | |
| */ | |
| extension Int: Num { | |
| var isNegative: Bool { return self < 0 } | |
| static func fromInt(intValue: Int) -> Int { | |
| return intValue | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment