Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

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. 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())
  2. 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
  3. 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!") }
  4. Phantom types protocol Currency {} enum GBP : Currency {}

    enum EUR : Currency {} enum USD : Currency {} struct Money<C : Currency> { let amount : NSDecimalNumber }
  5. 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)) }