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".

8162cb1dea89b7041ba5d67d1c5a01f2?s=128

Johannes Weiss

March 21, 2015
Tweet

Transcript

  1. Making the Illegal Impossible

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

    make sense?
  3. Making the Illegal Impossible

  4. Further Leveraging the Type System

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

    fill holes
  6. undefined can fill holes func undefined<T>(_ 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())
  7. Function Holes func parseIntFromString(input : String) -> Int? { let

    parsedInt = (undefined() as String -> Int?)(input) return parsedInt } func mayFail(x : Int) -> Result<Int> func addUpSuccesses(xs : [Int]) -> Int { let combine : (Int, Result<Int>) -> Int = undefined("fancy +") return map(xs, mayFail).reduce(0, combine:combine) } -> fatal error: undefined fancy +: file main.swift, line 214
  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!") }
  9. ! Phantoms

  10. Phantom types protocol Currency {} enum GBP : Currency {}

    enum EUR : Currency {} enum USD : Currency {} struct Money<C : Currency> { let amount : NSDecimalNumber }
  11. Phantom type example func convertGBPtoEUR(gbp:Money<GBP>) -> Money<EUR> { let forex

    : NSDecimalNumber = NSDecimalNumber(mantissa: 133263, exponent: -5, isNegative: false) return Money(amount:gbp.amount.decimalNumberByMultiplyingBy(forex)) }
  12. Thank you! @johannesweiss | johannes@jweiss.io