0
A swift introduction to
Giordano Scalzo
Closure Busker
iOS Dev
geek
giordano.scalzo@gmail.com
with different reactions
but also
From
To
What does Swift look like?
SHOW ME THE CODE!!!!!
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore +...
;
;
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
!
if optionalName {
greeting = "Hello, (optionalName!...
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
!
if let name = optionalName {
greeting = "Hello, (na...
if let upper =
john.residence?.address?.buildingIdentifier()?.uppercaseString {
println("John's uppercase building identif...
Playground
Switch on steroids
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add raisins."
case "cucumber", "wat...
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println("(0, 0) is at the origin")
case (_, 0):
println("((somePoin...
Functions and closures
func greet(name: String, #day: String) -> String {
return "Hello (name), today is (day)."
}
greet("Bob", day: "Wednesday")...
func greet(name: String, day: String) -> String {
return "Hello (name), today is (day)."
}
greet("Bob", "Wednesday")
Named...
Multiple result using tuples
func getGasPrices()->(Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
let (min, avg, ma...
Multiple result using tuples
func getGasPrices()->(Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
let gasPrices = g...
Functions are first class
type
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increme...
or a function parameter
func hasAnyMatches(list: Int[],
condition: Int -> Bool) -> Bool {
for item in list {
if condition(...
anonymous function
func hasAnyMatches(list: Int[],
condition: Int -> Bool) -> Bool {
for item in list {
if condition(item)...
func hasAnyMatches(list: Int[],
condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
...
func hasAnyMatches(list: Int[],
condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
...
Where are the classes?
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescript...
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
su...
class Square: NamedShape {
var sideLength: Double
init(sideLength len: Double, name: String) {
self.sideLength = len
super...
class Square: NamedShape {
var sideLength: Double
init(_ sideLength: Double, _ name: String) {
self.sideLength = sideLengt...
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
...
var perimeter: Double {
get {
return 3.0 * sideLe...
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var sq...
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The (rank.simpleDescription()) of...
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The (rank.simpleDescription()) of...
like classes, but passed by value...in a smarter way
classes are always passed by reference
structs are passed by reference, but automatically copied
when mutated
Struct are used as ValueTypes, data components manipulated
by classes
https://www.destroyallsoftware.com/talks/boundaries
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight,
Nine, Ten
case Jack, Queen, King
func simple...
enum ServerResponse {
case Result(String, String)
case Error(String)
}
Enumerations with a value associated
Enumerations with a value associated
let success = ServerResponse.Result("6:00 am", "8:09
pm")
let failure = ServerRespons...
Pattern matching to extract associated values
switch result {
case let .Result(sunrise, sunset):
let serverResponse = "Sun...
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
Protocols... like Interface in J...
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number (self)"
}
mutating func adjust() {
sel...
Generics
func repeatString(item: String, times: Int) -> String[]
{
var result = String[]()
for i in 0..times {
result += item
}
ret...
!
func repeatInt(item: Int, times: Int) -> Int[] {
var result = Int[]()
for i in 0..times {
result += item
}
return result...
func repeat<T>(item: T, times: Int) -> T[] {
var result = T[]()
for i in 0..times {
result += item
}
return result
}
repea...
Operator overload
@infix func +(t1: Int, t2: Int) -> Int{
return 3
}
!
@prefix func +(t1: Int) -> Int{
return 5
}
!
var a ...
But the most important feature, the only one
that you need to learn is...
Emoji!!!
For me (imvho) the most useful new
features are enumerations and pattern
matching
Unit Test support
XCTest
class RpnCalculatorKataTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super...
Quick
class PersonSpec: QuickSpec {
override class func exampleGroups() {
describe("Person") {
var person: Person?
beforeE...
And now...
Let's code
a Rpn Calculator
enum Key : String {
case One = "1" //...
case Enter = "enter"
case Plus = "+"
case Minus = "-"
}
!
protocol RpnCalculator ...
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
Upcoming SlideShare
Loading in...5
×

A swift introduction to Swift

45,097

Published on

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

1 Comment
196 Likes
Statistics
Notes
No Downloads
Views
Total Views
45,097
On Slideshare
0
From Embeds
0
Number of Embeds
25
Actions
Shares
0
Downloads
1,202
Comments
1
Likes
196
Embeds 0
No embeds

No notes for slide

Transcript of "A swift introduction to Swift"

  1. 1. A swift introduction to Giordano Scalzo Closure Busker
  2. 2. iOS Dev geek giordano.scalzo@gmail.com
  3. 3. with different reactions
  4. 4. but also
  5. 5. From
  6. 6. To
  7. 7. What does Swift look like?
  8. 8. SHOW ME THE CODE!!!!!
  9. 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. 10. ;
  11. 11. ;
  12. 12. var optionalName: String? = "John Appleseed" var greeting = "Hello!" ! if optionalName { greeting = "Hello, (optionalName!)" } Optional
  13. 13. var optionalName: String? = "John Appleseed" var greeting = "Hello!" ! if let name = optionalName { greeting = "Hello, (name)" } Optional
  14. 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. 15. Playground
  16. 16. Switch on steroids
  17. 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. 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. 19. Functions and closures
  20. 20. func greet(name: String, #day: String) -> String { return "Hello (name), today is (day)." } greet("Bob", day: "Wednesday") Named Parameters
  21. 21. func greet(name: String, day: String) -> String { return "Hello (name), today is (day)." } greet("Bob", "Wednesday") Named Parameters Optional
  22. 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. 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. 24. Functions are first class type
  25. 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. 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. 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. 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. 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. 30. Where are the classes?
  31. 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. 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. 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. 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. 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. 36. class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } } observable properties
  37. 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. 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. 39. like classes, but passed by value...in a smarter way
  40. 40. classes are always passed by reference structs are passed by reference, but automatically copied when mutated
  41. 41. Struct are used as ValueTypes, data components manipulated by classes
  42. 42. https://www.destroyallsoftware.com/talks/boundaries
  43. 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. 44. enum ServerResponse { case Result(String, String) case Error(String) } Enumerations with a value associated
  45. 45. Enumerations with a value associated let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.")
  46. 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. 47. protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } Protocols... like Interface in Java or... protocols in Objective-C
  48. 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. 49. Generics
  50. 50. func repeatString(item: String, times: Int) -> String[] { var result = String[]() for i in 0..times { result += item } return result } repeatString("knock", 4)
  51. 51. ! func repeatInt(item: Int, times: Int) -> Int[] { var result = Int[]() for i in 0..times { result += item } return result } repeatInt(42, 4)
  52. 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. 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. 54. But the most important feature, the only one that you need to learn is...
  55. 55. Emoji!!!
  56. 56. For me (imvho) the most useful new features are enumerations and pattern matching
  57. 57. Unit Test support
  58. 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. 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. 60. And now...
  61. 61. Let's code
  62. 62. a Rpn Calculator
  63. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×