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

Generics With Swift

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on. →

Generics With Swift

Avatar for akira hirakawa

akira hirakawa

April 16, 2015

Other Decks in Programming

Transcript

  1. swap two Int values func swapTwoInts(inout a: Int, inout b:

    Int) { let temporaryA = a a = b b = temporaryA }
  2. swap two Double values func swapTwoDoubles(inout a: Double, inout b:

    Double) { let temporaryA = a a = b b = temporaryA }
  3. swap two String values func swapTwoStrings(inout a: String, inout b:

    String) { let temporaryA = a a = b b = temporaryA }
  4. Generic function func swapTwoValues<T>(inout a: T, inout b: T) {

    let temporaryA = a a = b b = temporaryA }
  5. swap Int values var someInt = 3 var anotherInt =

    107 swapTwoValues(&someInt, &anotherInt)
  6. swap String values var someString = "hello" var anotherString =

    "world" swapTwoValues(&someString, &anotherString)
  7. can not var someInt = 3 var anotherString = "world"

    swapTwoValues(&someInt, &anotherString)
  8. but

  9. can

  10. swap two Any values func swapTwoValues(inout a: Any, inout b:

    Any) { let temporaryA = a a = b b = temporaryA }
  11. var a = 1 as Any var b = 2

    as Any swapTwoValues(&a, &b)
  12. var a = “a” as Any var b = “b”

    as Any swapTwoValues(&a, &b)
  13. but

  14. var a = 1 as Any var b = “a”

    as Any swapTwoValues(&a, &b)
  15. func executProtocol(p: Printable) -> Printable { p.description return p }

    func executeGenerics<T: Printable>(p: T) -> T { p.description return p }
  16. func executProtocol(p: Printable) -> Printable { return p } func

    executeGenerics<T: Printable>(p: T) -> T { return p }
  17. -> Printable you need to cast to use the return

    value var movie: Movie = … var p: Printable = executProtocol(movie) (p as Movie).show()
  18. -> T you don’t need to cast to use the

    value var movie: Movie = … movie = executeGenerics(movie) movie.show()
  19. but

  20. Generics doesn’t work on TableViewDeleate, TableViewDataSource because of a bug

    ds.respondsToSelector(“tableView:numberOfRo wsInSection:”) is false http://www.openradar.me/radar? id=5829206453780480
  21. AnyObject -> T var orm = { (json: AnyObject) ->

    User in … … return user } var orm = { (json: AnyObject) -> Media in … … return media }
  22. T -> () var handler = { ( item:User) ->

    () in … … } var handler = { (item:Media) -> () in … … }