Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Further Leveraging the Type System

Further Leveraging the Type System

My SwiftSummit 2015 lightning talk about further leveraging Swift's type system. Replaces the planned talk "Making the Illegal Impossible".

Johannes Weiss

March 21, 2015
Tweet

More Decks by Johannes Weiss

Other Decks in Technology

Transcript

  1. Making the Illegal
    Impossible

    View Slide

  2. Question about Type
    Does every value that can
    be created make sense?

    View Slide

  3. Making the Illegal
    Impossible

    View Slide

  4. Further Leveraging the
    Type System

    View Slide

  5. ⛳️
    When using strict types, we often have
    to (temporarily) fill holes

    View Slide

  6. undefined can fill holes
    func undefined(_ message:String="") -> T {
    fatalError("undefined \(message)")
    }
    Can be used for simple things like
    let a : String = undefined("special string")
    let b : Int = undefined("some int")
    let t = NSTimer(timeInterval: undefined(), target: undefined(),
    selector: undefined(), userInfo: undefined(),
    repeats: undefined())

    View Slide

  7. Function Holes
    func parseIntFromString(input : String) -> Int? {
    let parsedInt = (undefined() as String -> Int?)(input)
    return parsedInt
    }
    func mayFail(x : Int) -> Result
    func addUpSuccesses(xs : [Int]) -> Int {
    let combine : (Int, Result) -> Int = undefined("fancy +")
    return map(xs, mayFail).reduce(0, combine:combine)
    }
    -> fatal error: undefined fancy +: file main.swift, line 214

    View Slide

  8. Handling the impossible
    func lexicographicallyLowestString(x:String, y:String, z:String) -> String {
    let xyz = [x, y, z]
    return xyz.sorted({ $0 < $1 }).first ??
    undefined("the impossible happened!")
    }

    View Slide

  9. !
    Phantoms

    View Slide

  10. Phantom types
    protocol Currency {}
    enum GBP : Currency {}
    enum EUR : Currency {}
    enum USD : Currency {}
    struct Money {
    let amount : NSDecimalNumber
    }

    View Slide

  11. Phantom type example
    func convertGBPtoEUR(gbp:Money) -> Money {
    let forex : NSDecimalNumber = NSDecimalNumber(mantissa: 133263,
    exponent: -5,
    isNegative: false)
    return Money(amount:gbp.amount.decimalNumberByMultiplyingBy(forex))
    }

    View Slide

  12. Thank you!
    @johannesweiss | [email protected]

    View Slide