A swift introduction to Swift
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

A swift introduction to Swift

  • 39,908 views
Uploaded on

A quick introduction to Swift, the new language Apple introduced in WWDC14 to create apps for iOS and OSX

A quick introduction to Swift, the new language Apple introduced in WWDC14 to create apps for iOS and OSX

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
39,908
On Slideshare
38,847
From Embeds
1,061
Number of Embeds
21

Actions

Shares
Downloads
672
Comments
0
Likes
158

Embeds 1,061

http://www.scoop.it 384
https://twitter.com 305
http://blog.tareasplus.com 181
http://kazuhiromurota.com 60
http://hrishikeshballal.net 35
http://ideatosdotcom.wordpress.com 33
http://localhost 18
http://discourse.redwindsoftware.com 10
https://www.linkedin.com 8
https://hootsuite.scoop.it 6
http://gladyspintado.wordpress.com 5
http://gladyspintado.tumblr.com 4
http://hrishiballal.wordpress.com 3
http://www.linkedin.com 2
http://ranksit.com 1
http://plus.url.google.com 1
http://alexainformatica.tumblr.com 1
http://testsite1.grids.co 1
https://www.rebelmouse.com 1
https://content-preview.socialcast.com 1
http://news.google.com 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. A swift introduction to Giordano Scalzo Closure Busker
  • 2. iOS Dev geek giordano.scalzo@gmail.com
  • 3. with different reactions
  • 4. but also
  • 5. From
  • 6. To
  • 7. What does Swift look like?
  • 8. SHOW ME THE CODE!!!!!
  • 9. let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } teamScore
  • 10. ;
  • 11. ;
  • 12. var optionalName: String? = "John Appleseed" var greeting = "Hello!" ! if optionalName { greeting = "Hello, (optionalName!)" } Optional
  • 13. var optionalName: String? = "John Appleseed" var greeting = "Hello!" ! if let name = optionalName { greeting = "Hello, (name)" } Optional
  • 14. if let upper = john.residence?.address?.buildingIdentifier()?.uppercaseString { println("John's uppercase building identifier is (upper).") } else { println("I can't find John's address") } Optional Chaining
  • 15. Playground
  • 16. Switch on steroids
  • 17. let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add raisins." case "cucumber", "watercress": let vegetableComment = "sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy (x)?" default: let vegetableComment = "Soup." }
  • 18. let somePoint = (1, 1) switch somePoint { case (0, 0): println("(0, 0) is at the origin") case (_, 0): println("((somePoint.0), 0) is on the x-axis") case (0, _): println("(0, (somePoint.1)) is on the y-axis") case (-2...2, -2...2): println("((somePoint.0), (somePoint.1)) is inside the box") default: println("((somePoint.0), (somePoint.1)) is outside of the box") }
  • 19. Functions and closures
  • 20. func greet(name: String, #day: String) -> String { return "Hello (name), today is (day)." } greet("Bob", day: "Wednesday") Named Parameters
  • 21. func greet(name: String, day: String) -> String { return "Hello (name), today is (day)." } greet("Bob", "Wednesday") Named Parameters Optional
  • 22. Multiple result using tuples func getGasPrices()->(Double, Double, Double) { return (3.59, 3.69, 3.79) } let (min, avg, max) = getGasPrices() println("min is (min), max is (max)")
  • 23. Multiple result using tuples func getGasPrices()->(Double, Double, Double) { return (3.59, 3.69, 3.79) } let gasPrices = getGasPrices() println("min is (gasPrices.0), max is (gasPrices.2)")
  • 24. Functions are first class type
  • 25. func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) A function can be a return value
  • 26. or a function parameter func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, lessThanTen)
  • 27. anonymous function func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, { num in num < 10})
  • 28. func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers) { num in num < 10} anonymous function
  • 29. func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers) { $0 < 10} anonymous function
  • 30. Where are the classes?
  • 31. class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with (numberOfSides) sides." } }
  • 32. class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length (sideLength)." } } ! let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()
  • 33. class Square: NamedShape { var sideLength: Double init(sideLength len: Double, name: String) { self.sideLength = len super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length (sideLength)." } } ! let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()
  • 34. class Square: NamedShape { var sideLength: Double init(_ sideLength: Double, _ name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length (sideLength)." } } ! let test = Square(5.2, "my test square") test.area() test.simpleDescription()
  • 35. class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 ... var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } ... } calculated properties
  • 36. class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } } observable properties
  • 37. struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The (rank.simpleDescription()) of (suit.simpleDescription())" } } let threeOfSpades = Card(rank: Card.Three, suit: Card.Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() Structs
  • 38. struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The (rank.simpleDescription()) of (suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() Structs
  • 39. like classes, but passed by value...in a smarter way
  • 40. classes are always passed by reference structs are passed by reference, but automatically copied when mutated
  • 41. Struct are used as ValueTypes, data components manipulated by classes
  • 42. https://www.destroyallsoftware.com/talks/boundaries
  • 43. enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) } } } Enumerations on steroids
  • 44. enum ServerResponse { case Result(String, String) case Error(String) } Enumerations with a value associated
  • 45. Enumerations with a value associated let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.")
  • 46. Pattern matching to extract associated values switch result { case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at (sunrise) and sunset is at (sunset)." case let .Error(error): let serverResponse = "Failure... (error)" }
  • 47. protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } Protocols... like Interface in Java or... protocols in Objective-C
  • 48. extension Int: ExampleProtocol { var simpleDescription: String { return "The number (self)" } mutating func adjust() { self += 42 } } 7.simpleDescription extensions... like categories in Objective-C
  • 49. Generics
  • 50. func repeatString(item: String, times: Int) -> String[] { var result = String[]() for i in 0..times { result += item } return result } repeatString("knock", 4)
  • 51. ! func repeatInt(item: Int, times: Int) -> Int[] { var result = Int[]() for i in 0..times { result += item } return result } repeatInt(42, 4)
  • 52. func repeat<T>(item: T, times: Int) -> T[] { var result = T[]() for i in 0..times { result += item } return result } repeat("knock", 4) repeat(42, 3)
  • 53. Operator overload @infix func +(t1: Int, t2: Int) -> Int{ return 3 } ! @prefix func +(t1: Int) -> Int{ return 5 } ! var a = 20 var b = 111 ! a + b // 3 a - +b // 15
  • 54. But the most important feature, the only one that you need to learn is...
  • 55. Emoji!!!
  • 56. For me (imvho) the most useful new features are enumerations and pattern matching
  • 57. Unit Test support
  • 58. XCTest class RpnCalculatorKataTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testExample() { XCTAssert(true, "Pass") } func testPerformanceExample() { self.measureBlock() { } } }
  • 59. Quick class PersonSpec: QuickSpec { override class func exampleGroups() { describe("Person") { var person: Person? beforeEach { person = Person() } describe("greeting") { context("when the person is unhappy") { beforeEach { person!.isHappy = false } it("is lukewarm") { expect(person!.greeting).to.equal("Oh, hi.") expect(person!.greeting).notTo.equal("Hello!") } } } } } }
  • 60. And now...
  • 61. Let's code
  • 62. a Rpn Calculator
  • 63. enum Key : String { case One = "1" //... case Enter = "enter" case Plus = "+" case Minus = "-" } ! protocol RpnCalculator { var display : String[] { get } func press(key: Key) } https://github.com/gscalzo/RpnCalculatorKata