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

Swift: The mobile language that’s coming to the...

Swift: The mobile language that’s coming to the cloud

Ian Partridge

November 10, 2016
Tweet

More Decks by Ian Partridge

Other Decks in Programming

Transcript

  1. 2 Ian Partridge • Senior developer in Swift@IBM • Background

    in runtime systems • Java garbage collection • Runtime performance analysis • Full-stack debugging @ianpartridge @alfa
  2. 3 Agenda • Introducing Swift • History • Why Swift?

    • The Swift Language • Bringing Swift to the server • Concurrency • Web frameworks • Cloud deployment
  3. Introducing Swift • Swift is a new programming language, designed

    by Apple to be the future of development on iOS and macOS. • General purpose systems programming language • Safe • Fast • Expressive 4
  4. Safe • Type safe, but with inference • Definitive initialization

    of local variables • Immutability as a core language feature • No implicit type conversions • Objects cannot be null 5
  5. Expressive • Syntax inspired by C family • Plus modern

    features from scripting languages • Generics • Closures • Tuples • map() + filter() + reduce() 6
  6. Fast • Belongs to the C family of compiled native

    languages • Built on LLVM optimizing compiler • ARC provides memory management without GC pauses • Concurrency provided via Grand Central Dispatch framework 7
  7. Timeline 8 Date Event 2010? Work begins inside Apple June

    2014 (WWDC) 1.0-beta September 2014 1.0 June 2015 (WWDC) 2.0-beta September 2015 2.0 December 2015 Swift open-sourced on GitHub June 2016 (WWDC) 3.0-beta September 2016 3.0
  8. Trusted, permissive licence • Apache Software Licence v2.0 • Third

    most popular OSS licence • After MIT, GPLv2 • Includes patent licence requirements • Trusted by community and industry 12
  9. What’s included? • Compiler swiftc • REPL swift • Debugger

    lldb • Unit testing xctest • Concurrency libdispatch • Standard library stdlib • Foundation • Swift Package Manager 14
  10. The Swift Language print("Hello, world!") let event = ”Devoxx BE"

    print("Hello, \(event)") event = "Somewhere else" // ERROR var variableEvent = ”Devoxx UK" 20
  11. Control Flow let expenseCosts = [34.4, 30.99, 250.0] var sum:

    Double = 0 for expense in expenseCosts { sum += expense } print("total cost is \(sum)") 21
  12. Switch let flavour = "Vanilla" switch flavour { case "Chocolate":

    print("Quite nice") case "Strawberry", "Rum'n'raisin": print("Very nice") case let str where str.hasPrefix("Mint"): print("UGH!!!, I hate \(str)") default: print("No opinion about this") } 22
  13. Optionals 23 var name: String? = "Joe Bloggs" if let

    validName = name { print("Hello, \(validName)") } else { print("Anonymous, eh...") } let str = "42" let num = Int(str) if num != nil { print("Conversion successful - num is \(num!)") } if let num = Int(str) { print("Conversion successful - num is \(num)") } else { print("Conversion failed") }
  14. Optional Chaining 24 if variable.myOptional != nil { if variable.myOptional!.anotherOptional

    != nil { print(variable.myOptional!.anotherOptional!.item) } } if let result = variable.myOptional?.anotherOptional?.item { print(result) }
  15. Functions 25 func addInts(a: Int, b: Int) -> Int {

    return a + b } addInts(a: 1, b: 3) func addInts(_ a: Int, _ b: Int) -> Int { return a + b } addInts(1, 3) func move(from start: Point, to end: Point) -> Bool { /* code */ } move(from: a, to: b)
  16. Varargs 26 func max(numbers: Int...) -> Int { var max

    = numbers[0] for number in numbers { if number > max { max = number } } return max } max(1, 2, 3, 4, 5) // 5 max() // ERROR
  17. Tuples func minAndMax(numbers: Int...) -> (min: Int, max: Int) {

    var min = numbers[0] var max = numbers[0] for number in numbers { if number > max { max = number } else if number < min { min = number } } return (min, max) } let result = minAndMax(1, 2, 3, 4, 5) print(result.min) print(result.max) 27
  18. Closures let numbers = [1, 2, 3] numbers.map({ (number: Int)

    -> Int in return number * 5 }) // [5, 10, 15] numbers.map({ number in number * 5 }) numbers.map { $0 * 5 } 28
  19. Structs 29 struct Point { var x: Int var y:

    Int func description() -> String { return "x=\(x), y=\(y)" } } var coord = Point(x: 2, y: 4) var newCoord = coord coord.x = 4 print(coord.description()) // x=4, y=4 print(newCoord.description()) // x=2, y=4
  20. Enums 30 var status = ApprovalStatus.PendingOn("Joe Bloggs") status = .Approved("13213-4341321-2")

    switch status { case .PendingOn(let approver): print("Request pending on approval from \(approver)") case .Denied: print("Request DENIED") case .Approved(let code): print("Request approved - auth code \(code)") } enum ApprovalStatus { case PendingOn(String) case Denied case Approved(String) }
  21. Classes 31 class Square { var area: Double = 0

    init(sideLength: Double) { self.sideLength = sideLength } var sideLength: Double { get { return sqrt(area) } set { area = newValue * newValue } } }
  22. Protocols and Extensions 32 protocol Describable { func description() ->

    String } struct Car : Describable { func description() -> String { return "Goes vroom” } } extension Double : Describable { func description() -> String { return "Currently set to \(self)” } } let d: Double = 3 print(d.description()) // “Currently set to 3.0”
  23. IBM Swift Sandbox • Interactive sandbox for exploring Swift •

    Saves your work • Supports multiple versions of Swift • Deploys your Swift code in a Linux Docker container 33 https://swiftlang.ng.bluemix.net/
  24. Why Swift on the server? • Runtime characteristics • Performance

    • Memory usage • Developer experience • Isomorphic Development • Fun! 34
  25. Isomorphic Swift code 35 Create Swift Module Generate Swift Client

    APIs Kitura Linux Server Project Swagger REST API Deploy Deploy • Same module on client and server • Local or remote API calls • Automatically created Swagger APIs
  26. Apple Client Deployment Server/Cloud Deployment Application-Specific Cloud Services Client Facing

    App Bringing Swift to the Server Foundation Swift Swift Standard Library Core Foundation Dispatch PWQ C libs GLibc Foundation Swift Swift Standard Library Core Foundation Dispatch Darwin C libs Client-specific Libraries App Libraries Server-specific Libraries App Libraries Driving Towards Consistent Runtime across Clients/Servers Server-side Environments (Built with Foundation & Libdispatch)
  27. Grand Central Dispatch 37 a queue - FIFO put task

    into queue to execute dequeued tasks are being executed in wai8ng • Execute code concurrently on multicore hardware by submitting work to dispatch queues managed by the system.
  28. Grand Central Dispatch • Queue: abstract FIFO work container •

    Serial: work items executed one at a time • Parallel: work items dequeued in order but run simultaneously • Work: a Swift closure • Managed by the system • Work is executed on a thread pool managed by GCD • Work may execute on any thread 38
  29. Running work on queues import Dispatch let serialQueue = DispatchQueue(label:

    "serial queue") serialQueue.async { print("run on serial queue") } serialQueue.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(1)) { print("run on serial queue") } let concurrentQueue = DispatchQueue(label: "concurrent queue", attributes: .concurrent) concurrentQueue.async { print("run on concurrent queue") } 39
  30. Grouping work import Dispatch let queue = DispatchQueue(label: "group queue",

    attributes: .concurrent) let group = DispatchGroup() queue.async(group: group) { print("work 1") } queue.async(group: group) { print("work 2") } group.notify(queue: queue) { print("all work completed") } 40
  31. GCD in Swift 3 • New user-friendly API • Port

    to Linux • Depends on libpwq and libkqueue • Performance improvements 41
  32. Server APIs Work Group 43 • New community group to

    provide core server-side functionality • Base networking • TCP/IP • UDP • DNS • IPv6 • Security and Encryption • Ciphers • Keychain and certificate management • SSL/TLS • HTTP and WebSocket
  33. IBM Swift Package Catalog 44 https://packagecatalog.com/ • Create, share and

    discover new Swift packages • Explore dependencies • Check licenses • Star your favourite packages
  34. Kitura Web Framework http://github.com/IBM-Swift/Kitura 45 • Open source web framework

    for Swift on macOS and Linux • Inspired by Express for Node.js • Flexible routing • Pluggable middlewares • Easy to deploy
  35. Kitura Architecture 46 Web Framework Web Framework Source C Helpers

    & Interfaces Swift Libraries SwiftyJSON SwiftMongoDB Swift Binary Foundation Package Manager C Libraries Dispatch HttpParser HiRedis CURL PCRE2 Pluggable Components
  36. Developing a Kitura web application 47 myProject ├── Package.swift ├──

    Sources │ └── main.swift └── Tests $ mkdir myProject && cd myProject 2. Next, initialize this project as a new Swift package 1. First, we create a new project directory $ swift package init --type executable Basic Swift package directory structure:
  37. Developing a Kitura web application 48 import PackageDescription let package

    = Package( name: "myProject", dependencies: [ .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1, minor: 1) ] ) 3. Add Kitura as a dependency for your project (Package.swift):
  38. Developing a Kitura web application 49 Kitura.addHTTPServer(onPort: 8090, with: router)

    Kitura.run() let router = Router() router.get("/hello") { request, response, next in response.status(.OK).send("<h1>Hello, World!</h1>").end() } 6. Create and start an HTTPServer: 4. Add a router and a path: router.get("/hello.json") { request, response, next in response.status(.OK).send(json: JSON(["Hello": "World!"])).end() } 5. Add a JSON data route
  39. Developing a Kitura web application 50 import Kitura let router

    = Router() router.get("/hello") { request, response, next in response.status(.OK).send("<h1>Hello, World!</h1>").end() } router.get("/hello.json") { request, response, next in response.status(.OK).send(json: JSON(["Hello": "World!"])).end() } Kitura.addHTTPServer(onPort: 8090, with: router) Kitura.run() 7. Sources/main.swift should now look like this:
  40. Developing a Kitura web application 51 $ swift build 8.

    Compile: $ .build/debug/myFirstProject & 9. Run: 10. Open your browser: http://localhost:8090/hello http://localhost:8090/ http://localhost:8090/hello.json
  41. Get started quickly with Kitura • http://github.com/IBM-Swift/Kitura-Sample • `make run`

    • http://github.com/IBM-Swift/Kitura-Starter-Bluemix • `cf push` • http://github.com/IBM-Swift/swift-watson-sdk 52
  42. Adding a backend Apps need persistence – we can help

    you! • Apache Cassandra • https://github.com/IBM-Swift/Kassandra • Redis • https://github.com/IBM-Swift/Kitura-redis • CouchDB • https://github.com/IBM-Swift/Kitura-CouchDB 53
  43. Adding authentication via OAuth 2.0 • HTTP Basic Auth •

    https://github.com/IBM-Swift/Kitura-CredentialsHTTP • Facebook • https://github.com/IBM-Swift/Kitura-CredentialsFacebook • Google • https://github.com/IBM-Swift/Kitura-CredentialsGoogle • GitHub • https://github.com/IBM-Swift/Kitura-CredentialsGitHub 54
  44. TodoList demo app • A shared example to showcase backend

    tech stacks • http://todobackend.com/ • An example using Kitura to develop a Todo-Backend • https://github.com/IBM-Swift/Kitura-TodoList 56
  45. IBM Cloud Tools for Swift • Deployment made easy •

    Clone, code, push • Demo projects to try 57 http://cloudtools.bluemix.net
  46. The future of Kitura? • Next-gen transport protocols • WebSockets

    / socket.io • HTTP/2 • Backend abstraction • More performance • Monitoring • Clustering 59
  47. The future of Swift on Linux? • Completing the implementation

    of Foundation • Libdispatch performance and scalability improvements • Building a vibrant Swift on Linux community • Server-side packages in the rapidly-growing SPM ecosystem • IDE support • More cloud integration • Exploring the Swift “sweet-spot” • Linux-driven enhancements to Swift itself? 60