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

The Secret Life of Types in Swift

The Secret Life of Types in Swift

Types are important? Yes they are! And they can form the whole behaviour of a language - like Swift. This talk deals with the very type essentials and gives a first glance under the hood of the Swift type system.

233522f6a55d788094a97a4be3d37b23?s=128

manu rink

March 09, 2017
Tweet

More Decks by manu rink

Other Decks in Programming

Transcript

  1. Manuela Rink Technical Evangelist @ The secret life of types

    in Swift
  2. What is Swift?

  3. Swift?

  4. Swift?!!?

  5. Swift!!!

  6. Disclaimer At least intermediate experience with reading and writing different

    programming languages and a basic understanding of type systems. Yes, we will see code – because programming! ~LVL300-400 It’s not impolite to leave now – no kitten memes to miss here!
  7. The Language

  8. v4 One-side ranges Comfortable encoding/decoding Multi-line string literals Improved key-value

    coding Strings as collections More powerful dictionaries Downwards compatibility*
  9. Compiler version bound to Xcode version 2014-08-18 Swift 1.0 2014-10-16

    Swift 1.1 2015-04-08 Swift 1.2 2015-09-16 Swift 2 2015-10-20 Swift 2.1 2015-12-03 open sourced 2016-03-21 Swift 2.2 2016-06-12 Swift 2.3 2016-09-13 Swift 3 * 2016-10-27 Swift 3.0.1 * Compiler for Swift 3 and 2.3 offered in Xcode 8 Code adjustments No downwards compatiblity
  10. IEEE Spectrum Language Ranking 2017 https://spectrum.ieee.org/computing/software/the-2017-top-programming-languages IEEE Spectrum Overall Readers

  11. IEEE Spectrum Language Ranking 2017 https://spectrum.ieee.org/computing/software/the-2017-top-programming-languages IEEE Spectrum Trending

  12. IEEE Spectrum Language Ranking 2017 https://spectrum.ieee.org/computing/software/the-2017-top-programming-languages IEEE Spectrum Mobile only

  13. ? no fixed ABI with v3.0.1 update IDE – adapt

    code compatibility with Swift based frameworks
  14. The good old… Named parameters Structs and Enums Blocks/Closures Automatic

    memory management The shiny new… Inferred types Modules make headers obsolete By default nothing can be nil Tuples & multiple return values
  15. The sugar No semicolon Byebye (most of you) square brackets

    The promise Swift code is save by design. Lightning fast … and fun to learn because of its shortness!
  16. ?! ! ? !!!!11eleven !? ? ? ! ? ?

    ! ? ! ? ! ? TYPES TYPES EVERYWHERE
  17. It’s all about types

  18. None
  19. There shall be $noRoot and never will there be nil*

    Swift doesn’t have a specific root type like e.g. Obj-C, Java… Empty values are not allowed* *almost
  20. Obj-C Java java.lang.Object java.lang.Number java.lang.Integer conforms to: Serializable, Comparable<Integer> NSObject

    NSValue NSNumber conforms to: CKRecordCalue, CVarArg, Equatable, ExpressibleByBooleanLiteral, ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, Hashable, NSFetchRequestResult conforms to: BitwiseOperations, CVarArg, Comparable, CustomPlaygroundQuickLookable, CustomReflectable, CustomStringConvertible, Equatable, ExpressibleByIntegerLiteral, Hashable, Integer, IntegerArithmetic, MirrorPath, SignedInteger, SignedNumber, Strideable, _Incrementable, _Integer, _IntegerArithmetic, _SignedInteger Swift Int
  21. Int Type in Swift http://swiftdoc.org/v3.1/

  22. Float Dictionary http://swiftdoc.org/v3.1/

  23. Dive into types

  24. No dedicated type root Type conforms to protocols instead of

    heavy inheritance Super loose coupling Nice separation of concerns Clean architecture … and there are just two types of types! Named types & compound types* *which can contain named types
  25. None
  26. Named Types

  27. Named types have ... names!

  28. … } Int gets extended by a lot of other

    types. Conforming protocol list is rather short. But conforming / inheritance hierarchy is quite complex. Extend to your needs!
  29. Int Type in Swift http://swiftdoc.org/v3.1/

  30. Compound Types

  31. Compound types have … no names And that’s a good

    thing!
  32. var greatTuple = (x: 10, y: 20) greatTuple = (x:

    12, y: 50) greatTuple = (0,0) print (greatTuple.0 + “==“ + greatTuple.x) greatTuple = (xCoord: 10, yCoord: 20) greatTuple = (x: “manu”, y: 20) Tuple Type Ad hoc type definition for named multiple values with type safety
  33. func randomColorScheme () -> (fg: UIColor, bg: UIColor) { let

    foreground = randomForegroundColor() let background = randomBackgroundColor() return (foreground, background) } let colorScheme = randomColorScheme() view.backgroundColor = colorScheme.bg Tuple Type Use to return multiple values from a function
  34. var point = (13, 12) typealias Point = (Int, Int)

    var point = Point(10, 12) typealias Point = (x: Int, y: Int) var myPoint = Point(x: 10, y: 12) var myOtherPoint = Point(10, 12) var myRealPoint = (10, 12) typealias CGPoint = (String, String) var thePoint = CGPoint(“this is”, “dangerous”) Tuple Type Give them names… … with typealias
  35. () It’s Void! public typealias Void = () let myAge

    : (Int) = (23) let myAge : Int = 23 (Type) == Type
  36. func processPerson (withID: Int) -> () {} func processVIP (withID:

    Int) {} struct Person { firstname : String lastname : String } func nameForPerson (withID: Int) -> (name: String, age: Int) {} func nameForPerson (withID: Int) -> (Person) {} func nameForPerson (withID: Int) -> Person {} func detailsForPerson (withID: Int) -> (obj: Person, age: Int) {} Function Type Defines the type of a function or method. Combines the parameter and return type with -> Can be composed of named and compound types again
  37. func whereToGo (ahead : Bool) -> (Int) -> Int {

    func goAhead (input: Int) -> Int { return input + 1 } func goBack (input: Int) -> Int { return input - 1 } return ahead ? goAhead : goBack } var stepsToHome = -3 let goHome = whereToGo(ahead: stepsToHome < 0) while stepsToHome != 0 { print("steps to home: \(abs(stepsToHome))") stepsToHome = goHome(stepsToHome) } Function Type Global functions vs. nested functions… … and their strange looking return types. (Bool) -> (Int) -> Int in inner in out
  38. Use functions on variables func goHome (ahead: Bool) {} func

    stepsToHome () -> Int { return steps } var f = goHome f = stepsToHome // type of f is (Bool) -> Void Variadic parameters as arrays func printAll(_ numbers: Int...) -> Int { for number in numbers { print ( “the number \(number)”) } }
  39. Closures parent concept of global and nested functions { (parameters)

    -> return type in // do funky stuff } let names = [”Igor”, ”Horst”, ”Manu”, ”Alex”, ”David”] func ascending (_ s1: String, _ s2: String) -> Bool { return s1 < s2 } var ascendingNames = names.sorted(by: ascending) ascendingNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 < s2 }) ascendingNames = names.sorted(by: { s1, s2 in s1 < s2}) ascendingNames = names.sorted(by: {$0 < $1}) Shorten your code (at the expense of readability) ascendingNames = names.sorted(by: <)
  40. http://fuckingblocksyntax.com/ http://fuckingclosuresyntax.com/

  41. the sugar on the top

  42. ?! Don’t be afraid … it’s just Optionals public enum

    ImplicitlyUnwrappedOptional<Wrapped> : ExpressibleByNilLiteral { /// The absence of a value. Typically written using the nil literal, `nil`. case none /// The presence of a value, stored as `Wrapped`. case some(Wrapped) /// Creates an instance that stores the given value. public init(_ some: Wrapped) /// Creates an instance initialized with `nil`. /// /// Do not call this initializer directly. It is used by the compiler when /// you initialize an `Optional` instance with a `nil` literal. For example: /// let i: Index! = nil public init(nilLiteral: ()) }
  43. var myName : Optional<String> myName = "manu” var theName =

    “manu” if myName != nil && theName != nil { print(myName) print(theName) } “Optional(“manu”)” “manu”
  44. var myName : String? = “manu” print(myName) print(myName!) if let

    name = myName { print(name) } “Optional(“manu”)” “manu” “manu”
  45. var name : String? = "manu" guard let myName =

    name else { print("empty name - can't proceed") return } print(myName) “manu”
  46. var myName : String! myName = “manu” print(myName) “manu”

  47. One more thing...

  48. None
  49. This is the end ...

  50. None
  51. Think about Code changes because of no yet fixed ABI

    Swift version tied to Xcode version Swift based frameworks / libraries Longer compilation / building time Getting used to the ”swifty way” Swift, YEY of NEY … ? Have fun with Short and descriptive syntax (if you use it) Type safety Strong compiler time validation … definitively YEY!
  52. None
  53. None
  54. Merci :) Manu Rink Technical Evangelist marink@microsoft.com @codeprincess says

  55. Sources All memes from https://openclipart.org Rage face from http://knowyourmeme.com/ Not

    bad meme from http://nibler.ru/uploads/users/4233/2012-01- 31/%D0%BE%D0%B1%D0%BC%D0%B0%D0%BD%D1%83%D1%82%D1%8C- _83631761.jpg Taylor Swift article from https://mobilebusinessinsights.com/2016/10/more-than-a- blank-space-what-swift-design-has-in-common-with-taylor-swift/ Taylor Swift memes from http://giphy.com All Swift types scribble graphics © Manuela Rink