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

Switch to Swift presented at mix-it2015

Switch to Swift presented at mix-it2015

Corinne Krych

April 17, 2015
Tweet

More Decks by Corinne Krych

Other Decks in Programming

Transcript

  1. Why Swift? Apple goals with Swift: • modern • easy-to-read

    code • safer code • compatible with existing Objective-C
  2. Syntax: melting pot Tip 1 "Of course, it also greatly

    benefited from the experiences hard- won by many other languages (…) Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list." Groovy Scala Rust C# ObjC Haskell
  3. var shoppingList = ["catfish", "water"] shoppingList[1] = "bottle of water"

    var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" var emptyMap = [:] var emptyList = [] def shoppingList = ["catfish", "water"] shoppingList[1] = "bottle of water" def occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" def emptyMap = [:] def emptyList = [] Resemblance to…
  4. var shoppingList = ["catfish", "water"] shoppingList[1] = "bottle of water"

    var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" var emptyMap = [:] var emptyList = [] def shoppingList = ["catfish", "water"] shoppingList[1] = "bottle of water" def occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" def emptyMap = [:] def emptyList = [] Resemblance to…
  5. Resemblance to… func f<T>(x: T) -> T {...} func g(x:

    A) {} func h<T: A>(x: T) -> T {...} func k(x:Int = 0) {} def f[T](x: T): T = ... def g(x: A) {} def h[T <: A](x: T): T ... def k(x: Int =0)
  6. Resemblance to… func f<T>(x: T) -> T {...} func g(x:

    A) {} func h<T: A>(x: T) -> T {...} func k(x:Int = 0) {} def f[T](x: T): T = ... def g(x: A) {} def h[T <: A](x: T): T ... def k(x: Int =0)
  7. Resemblance to… var a = "some text" var b =

    "some text" if a == b { println("The strings are equal") } if a.hasPrefix("some") { println("Starts with some") } if a.hasSuffix("some") { println("Endss with some") } a = "some text" b = "some text" if a == b: print("The strings are equal") if a.startswith("some"): print("Starts with some") if a.endswith("some"): print("Ends with some")
  8. Resemblance to… var a = "some text" var b =

    "some text" if a == b { println("The strings are equal") } if a.hasPrefix("some") { println("Starts with some") } if a.hasSuffix("some") { println("Endss with some") } a = "some text" b = "some text" if a == b: print("The strings are equal") if a.startswith("some"): print("Starts with some") if a.endswith("some"): print("Ends with some")
  9. Resemblance to… var dict = Dictionary<String, String>() var dict2 =

    ["TYO": "Tokyo", "DUB": “Dublin"] for (key, value) in dict { … … } var dict = new Dictionary<string, string>(); var dict2 = new Dictionary<string, string> { { "TYO", "Tokyo" }, { "DUB", "Dublin" } }; foreach(var item in dict) { var key = item.Key; var value = item.Value; }
  10. Resemblance to… var dict = Dictionary<String, String>() var dict2 =

    ["TYO": "Tokyo", "DUB": “Dublin"] for (key, value) in dict { … … } var dict = new Dictionary<string, string>(); var dict2 = new Dictionary<string, string> { { "TYO", "Tokyo" }, { "DUB", "Dublin" } }; foreach(var item in dict) { var key = item.Key; var value = item.Value; }
  11. Resemblance to… let success = { (res: A) -> ()

    in println("succeeded") } let failure = { (res: A) -> () in println("FH init failed") } FH(success: success, failure: failure) void (^success)(A *) = ^(A * res) { NSLog(@"succeeded"); }; void (^failure)(id) = ^(A * res) { NSLog(@"FH init failed"); }; [FH initWithSuccess:success AndFailure:failure];
  12. Resemblance to… let success = { (res: A) -> ()

    in println("succeeded") } let failure = { (res: A) -> () in println("FH init failed") } FH(success: success, failure: failure) void (^success)(A *) = ^(A * res) { NSLog(@"succeeded"); }; void (^failure)(id) = ^(A * res) { NSLog(@"FH init failed"); }; [FH initWithSuccess:success AndFailure:failure];
  13. Resemblance to… let success = { (res: A) -> ()

    in println("succeeded") } let failure = { (res: A) -> () in println("FH init failed") } FH(success: success, failure: failure) void (^success)(A *) = ^(A * res) { NSLog(@"succeeded"); }; void (^failure)(id) = ^(A * res) { NSLog(@"FH init failed"); }; [FH initWithSuccess:success AndFailure:failure]; http://goshdarnblocksyntax.com/
  14. Properties Computed properties do not store a value. Instead, they

    provide a getter and an optional setter to retrieve and set other properties and values indirectly. Tip 4
  15. /** An OAuth2Session implementation to store OAuth2 metadata using Keychain.

    */ public class TrustedPersistantOAuth2Session: OAuth2Session { private let keychain: KeychainWrap /** The access token. The information is read securely from Keychain. */ public var accessToken: String? { get { return self.keychain.read(self.accountId, tokenType: .AccessToken) } set(value) { if let unwrappedValue = value { let result = self.keychain.save(self.accountId, tokenType: .AccessToken, value: unwrappedValue) } } } Computed properties aerogear-ios-oauth2
  16. /** An OAuth2Session implementation to store OAuth2 metadata using Keychain.

    */ public class TrustedPersistantOAuth2Session: OAuth2Session { private let keychain: KeychainWrap /** The access token. The information is read securely from Keychain. */ public var accessToken: String? { get { return self.keychain.read(self.accountId, tokenType: .AccessToken) } set(value) { if let unwrappedValue = value { let result = self.keychain.save(self.accountId, tokenType: .AccessToken, value: unwrappedValue) } } } Computed properties aerogear-ios-oauth2
  17. /** An OAuth2Session implementation to store OAuth2 metadata using Keychain.

    */ public class TrustedPersistantOAuth2Session: OAuth2Session { private let keychain: KeychainWrap /** The access token. The information is read securely from Keychain. */ public var accessToken: String? { get { return self.keychain.read(self.accountId, tokenType: .AccessToken) } set(value) { if let unwrappedValue = value { let result = self.keychain.save(self.accountId, tokenType: .AccessToken, value: unwrappedValue) } } } Computed properties aerogear-ios-oauth2
  18. /** An OAuth2Session implementation to store OAuth2 metadata using Keychain.

    */ public class TrustedPersistantOAuth2Session: OAuth2Session { private let keychain: KeychainWrap /** The access token. The information is read securely from Keychain. */ public var accessToken: String? { get { return self.keychain.read(self.accountId, tokenType: .AccessToken) } set(value) { if let unwrappedValue = value { let result = self.keychain.save(self.accountId, tokenType: .AccessToken, value: unwrappedValue) } } } Computed properties aerogear-ios-oauth2
  19. var jsonString = "[{\"id\":1, \"name\": \"Eliott\"}," + "{\"id\":2, \"name\": \"Emilie\"}]"

    var data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) let jsonObject: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) // Handling JSON in Swift with optional and type casting if let personsArray = jsonObject as? NSArray { if let firstPerson = personsArray[0] as? NSDictionary { if let name = firstPerson["name"] as? NSString { println("First person name is \(name)") } } } Problem to solve: JSON SwitftyJSON
  20. var jsonString = "[{\"id\":1, \"name\": \"Eliott\"}," + "{\"id\":2, \"name\": \"Emilie\"}]"

    var data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) let jsonObject: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) // Handling JSON in Swift with optional and type casting if let personsArray = jsonObject as? NSArray { if let firstPerson = personsArray[0] as? NSDictionary { if let name = firstPerson["name"] as? NSString { println("First person name is \(name)") } } } Problem to solve: JSON SwitftyJSON // Using SwiftyJSON let json = JSON(data: data!) if let userName = json[0]["name"].string { println("First person name is \(userName)”) }
  21. public enum JSON { //private type number case ScalarNumber(NSNumber) //private

    type string case ScalarString(NSString) //private type sequence case Sequence([JSON]) //private type mapping case Mapping([String: JSON]) //private type null case Null(NSError?) . . . } Enum associated values SwitftyJSON
  22. public enum JSON { //private type number case ScalarNumber(NSNumber) //private

    type string case ScalarString(NSString) //private type sequence case Sequence([JSON]) //private type mapping case Mapping([String: JSON]) //private type null case Null(NSError?) . . . } Enum associated values SwitftyJSON public init(object: AnyObject) { switch object { case let number as NSNumber: self = .ScalarNumber(number) case let string as NSString: self = .ScalarString(string) case let null as NSNull: self = .Null(nil) case let array as [AnyObject]: self = .Sequence(array) case let dictionary as [String: AnyObject]: self = .Mapping(dictionary) default: self = .Null(NSError(…)) } }
  23. SwitftyJSON Subscript // Using SwiftyJSON let json = JSON(data: data!)

    if let userName = json[0]["name"].string { println("First person name is \(userName)") }
  24. public subscript(index: Int) -> JSON { get { switch self

    { case .Sequence(let array): if array.count > index { return array[index] } else { return .Null(NSError(…)) } default: return .Null(NSError(…)) } } } SwitftyJSON Subscript // Using SwiftyJSON let json = JSON(data: data!) if let userName = json[0]["name"].string { println("First person name is \(userName)") }
  25. public var string: String? { get { switch self {

    case .ScalarString(let string): return string default: return nil } } } public subscript(index: Int) -> JSON { get { switch self { case .Sequence(let array): if array.count > index { return array[index] } else { return .Null(NSError(…)) } default: return .Null(NSError(…)) } } } SwitftyJSON Subscript // Using SwiftyJSON let json = JSON(data: data!) if let userName = json[0]["name"].string { println("First person name is \(userName)") }
  26. Surrounded by clones Almost all types in Swift are value

    types, including arrays, dictionary, numbers, booleans, tuples, and enums. Classes are the exception rather than the rule. Tip 6
  27. Functions in Swift are first-class values, i.e. functions may be

    passed as arguments to other functions, and functions may return new functions. Tip 7 Functions, methods closures
  28. Methods @implementation Greetings … - (NSString *)helloFirstname:(NSString *)firstname lastname:(NSNumber *)lastname

    { return [[NSString alloc] initWithFormat:@"hello, %@ %@", firstname, lastname]; } [self helloFirstName:@"Isabel" lastname:@"Dupont"];
  29. Methods @implementation Greetings … - (NSString *)helloFirstname:(NSString *)firstname lastname:(NSNumber *)lastname

    { return [[NSString alloc] initWithFormat:@"hello, %@ %@", firstname, lastname]; } [self helloFirstName:@"Isabel" lastname:@"Dupont"]; class Greetings { func helloFirstname(firstname: String, lastname: String) -> String { return "Hello \(firstname) \(lastname)" } } let morning = Greetings() morning.helloFirstname("Isabel", lastname: "Dupont")
  30. func hello(firstname: String, lastname: String) -> String { return "hello,

    \(firstname) \(lastname)" } hello("Isabel", "Dupont") Functions
  31. func hello(firstname: String, lastname: String) -> String { return "hello,

    \(firstname) \(lastname)" } hello("Isabel", "Dupont") Functions func hello(firstname: String, #lastname: String) -> String { return "Hello \(firstname) \(lastname)." } hello("Isabel", lastname: "Dupont")
  32. func hello(firstname: String, lastname: String) -> String { return "hello,

    \(firstname) \(lastname)" } hello("Isabel", "Dupont") Functions func hello(firstname: String, #lastname: String) -> String { return "Hello \(firstname) \(lastname)." } hello("Isabel", lastname: "Dupont") func hello(firstname: String, lastname lastname: String) -> String { return "Hello \(firstname) \(lastname)." } hello("Isabel", lastname: "Dupont")
  33. when to use them in real life? Person { "firstname":

    "john", "lastname": "doe", "address": { "street": "Buch Street", "poBox": 123, "city": "Glasgow", "country": "UK" } } aerogear-ios-jsonsz
  34. when to use them in real life? Person { "firstname":

    "john", "lastname": "doe", "address": { "street": "Buch Street", "poBox": 123, "city": "Glasgow", "country": "UK" } } class Person { var firstname: String? var lastname: String var address: Address? } class Address { var street: String var poBox: Int var city: String var country: String } aerogear-ios-jsonsz
  35. when to use them in real life? Person { "firstname":

    "john", "lastname": "doe", "address": { "street": "Buch Street", "poBox": 123, "city": "Glasgow", "country": "UK" } } class Person { var firstname: String? var lastname: String var address: Address? } class Address { var street: String var poBox: Int var city: String var country: String } class Person: JSONSerializable { var firstname: String? var lastname: String var address: Address? required init() {} class func map(source: JsonSZ, object: Person) { object.firstname <= source["firstname"] object.lastname <= source["lastname"] object.address <= source["address"] } } aerogear-ios-jsonsz
  36. when to use them in real life? Person { "firstname":

    "john", "lastname": "doe", "address": { "street": "Buch Street", "poBox": 123, "city": "Glasgow", "country": "UK" } } class Person { var firstname: String? var lastname: String var address: Address? } class Address { var street: String var poBox: Int var city: String var country: String } class Person: JSONSerializable { var firstname: String? var lastname: String var address: Address? required init() {} class func map(source: JsonSZ, object: Person) { object.firstname <= source["firstname"] object.lastname <= source["lastname"] object.address <= source["address"] } } aerogear-ios-jsonsz // serialize from json var serializer = JsonSZ() let developer:Person = serializer.fromJSON(developerJSON, to: Person.self) XCTAssertTrue(developer.firstname == "john") XCTAssertTrue(developer.lastname == "doe")
  37. it’s all about type… public func <=(inout left: String?, right:

    JsonSZ) { if let value = right.value { field = value as? String } } aerogear-ios-jsonsz
  38. it’s all about type… public func <=(inout left: String?, right:

    JsonSZ) { if let value = right.value { field = value as? String } } aerogear-ios-jsonsz public func <=(inout left: Int?, right: JsonSZ) { if let value = right.value { field = value as? Int } } public func <=(inout left: Bool?, right: JsonSZ) { if let value = right.value { field = value as? Bool } }
  39. Go Generics Generics allow a programmer to tell their functions

    and classes: “I am going to give you a type later and I want you to enforce that type everywhere I specify.” Tip 8
  40. it’s all about type… public func <=<T>(inout left: T?, right:

    JsonSZ) { if let value: AnyObject = right.value { switch T.self { case is String.Type, is Bool.Type, is Int.Type, is Double.Type, is Float.Type: field = value as? T . . . default: field = nil return } } } aerogear-ios-jsonsz
  41. it’s all about type… public func <=<T>(inout left: T?, right:

    JsonSZ) { if let value: AnyObject = right.value { switch T.self { case is String.Type, is Bool.Type, is Int.Type, is Double.Type, is Float.Type: field = value as? T . . . default: field = nil return } } } public func <=<T: JSONSerializable>(inout left: T?, right: JsonSZ) { if let value = right.value as? [String: AnyObject] { field = JsonSZ().fromJSON(value, to: T.self) } } aerogear-ios-jsonsz
  42. extension String { public func urlEncode() -> String { let

    encodedURL = CFURLCreateStringByAddingPercentEscapes(nil, self as NSString, nil, "!@#$%&*'();:=+,/?[]", CFStringBuiltInEncodings.UTF8.rawValue) return encodedURL as String } } aerogear-ios-http Extend behaviour
  43. class MyViewController: UIViewController { // class stuff here } //

    MARK: - UITableViewDataSource extension MyViewController: UITableViewDataSource { // table view data source methods } // MARK: - UIScrollViewDelegate extension MyViewController: UIScrollViewDelegate { // scroll view delegate methods } class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate { // all methods } To be stylish ;)
  44. Mocking yourself func testRequestAccessWithAuthzCodeFlow() { let expectation = expectationWithDescription("AccessRequestWithAuthzFlow"); let

    googleConfig = . . . var mock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2Session()) mock.requestAccess { (response: AnyObject?, error:NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as String, “response with access token") expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } aerogear-ios-oauth2
  45. Mocking yourself func testRequestAccessWithAuthzCodeFlow() { let expectation = expectationWithDescription("AccessRequestWithAuthzFlow"); let

    googleConfig = . . . var mock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2Session()) mock.requestAccess { (response: AnyObject?, error:NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as String, “response with access token") expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } aerogear-ios-oauth2
  46. Mocking yourself func testRequestAccessWithAuthzCodeFlow() { let expectation = expectationWithDescription("AccessRequestWithAuthzFlow"); let

    googleConfig = . . . var mock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2Session()) mock.requestAccess { (response: AnyObject?, error:NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as String, “response with access token") expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } class OAuth2ModulePartialMock: OAuth2Module { override func refreshAccessToken( completionHandler:(AnyObject?, NSError?) -> ()) { completionHandler("NEW_ACCESS_TOKEN", nil) } override func requestAuthorizationCode( completionHandler: (AnyObject?, NSError?) -> ()) { completionHandler("ACCESS_TOKEN", nil) } } aerogear-ios-oauth2
  47. Mocking yourself func testRequestAccessWithAuthzCodeFlow() { let expectation = expectationWithDescription("AccessRequestWithAuthzFlow"); let

    googleConfig = . . . var mock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2Session()) mock.requestAccess { (response: AnyObject?, error:NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as String, “response with access token") expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } public class MockOAuth2Session: OAuth2Session { public override var refreshToken: String? { get {return nil} set(data) {} } public override func tokenIsNotExpired() -> Bool { return false } } class OAuth2ModulePartialMock: OAuth2Module { override func refreshAccessToken( completionHandler:(AnyObject?, NSError?) -> ()) { completionHandler("NEW_ACCESS_TOKEN", nil) } override func requestAuthorizationCode( completionHandler: (AnyObject?, NSError?) -> ()) { completionHandler("ACCESS_TOKEN", nil) } } aerogear-ios-oauth2
  48. Mocking yourself func testRequestAccessWithAuthzCodeFlow() { let expectation = expectationWithDescription("AccessRequestWithAuthzFlow"); let

    googleConfig = . . . var mock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2Session()) mock.requestAccess { (response: AnyObject?, error:NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as String, “response with access token") expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } public class MockOAuth2Session: OAuth2Session { public override var refreshToken: String? { get {return nil} set(data) {} } public override func tokenIsNotExpired() -> Bool { return false } } class OAuth2ModulePartialMock: OAuth2Module { override func refreshAccessToken( completionHandler:(AnyObject?, NSError?) -> ()) { completionHandler("NEW_ACCESS_TOKEN", nil) } override func requestAuthorizationCode( completionHandler: (AnyObject?, NSError?) -> ()) { completionHandler("ACCESS_TOKEN", nil) } } aerogear-ios-oauth2
  49. Mocking yourself func testRequestAccessWithAuthzCodeFlow() { let expectation = expectationWithDescription("AccessRequestWithAuthzFlow"); let

    googleConfig = . . . var mock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2Session()) mock.requestAccess { (response: AnyObject?, error:NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as String, “response with access token") expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } public class MockOAuth2Session: OAuth2Session { public override var refreshToken: String? { get {return nil} set(data) {} } public override func tokenIsNotExpired() -> Bool { return false } } class OAuth2ModulePartialMock: OAuth2Module { override func refreshAccessToken( completionHandler:(AnyObject?, NSError?) -> ()) { completionHandler("NEW_ACCESS_TOKEN", nil) } override func requestAuthorizationCode( completionHandler: (AnyObject?, NSError?) -> ()) { completionHandler("ACCESS_TOKEN", nil) } } aerogear-ios-oauth2