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

The Secret Life of Types in Swift

manu rink
March 09, 2017

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.

manu rink

March 09, 2017
Tweet

More Decks by manu rink

Other Decks in Programming

Transcript

  1. 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!
  2. v4 One-side ranges Comfortable encoding/decoding Multi-line string literals Improved key-value

    coding Strings as collections More powerful dictionaries Downwards compatibility*
  3. 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
  4. ? no fixed ABI with v3.0.1 update IDE – adapt

    code compatibility with Swift based frameworks
  5. 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
  6. 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!
  7. ?! ! ? !!!!11eleven !? ? ? ! ? ?

    ! ? ! ? ! ? TYPES TYPES EVERYWHERE
  8. 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
  9. 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
  10. 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
  11. … } 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!
  12. 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
  13. 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
  14. 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
  15. () It’s Void! public typealias Void = () let myAge

    : (Int) = (23) let myAge : Int = 23 (Type) == Type
  16. 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
  17. 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
  18. 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)”) } }
  19. 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: <)
  20. ?! 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: ()) }
  21. var myName : Optional<String> myName = "manu” var theName =

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

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

    name else { print("empty name - can't proceed") return } print(myName) “manu”
  24. 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!
  25. 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