SlideShare a Scribd company logo
1 of 84
Download to read offline
A swift introduction to
Giordano Scalzo
Closure Busker
iOS Dev
geek
giordano.scalzo@gmail.com
A swift introduction to Swift
A swift introduction to Swift
with different reactions
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
but also
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift
From
To
What does Swift look like?
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
SHOW ME THE CODE!!!!!
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
teamScore
;
;
A swift introduction to Swift
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
!
if optionalName {
greeting = "Hello, (optionalName!)"
}
Optional
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
!
if let name = optionalName {
greeting = "Hello, (name)"
}
Optional
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
Playground
A swift introduction to Swift
Switch on steroids
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."
}
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")
}
Functions and closures
func greet(name: String, #day: String) -> String {
return "Hello (name), today is (day)."
}
greet("Bob", day: "Wednesday")
Named Parameters
func greet(name: String, day: String) -> String {
return "Hello (name), today is (day)."
}
greet("Bob", "Wednesday")
Named Parameters Optional
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)")
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)")
Functions are first class
type
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
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)
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})
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
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
Where are the classes?
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with (numberOfSides) sides."
}
}
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()
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()
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()
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
...
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
...
}
calculated properties
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
}
observable properties
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
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
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 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
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 = ServerResponse.Error("Out of cheese.")
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)"
}
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
Protocols... like Interface in Java or... protocols in Objective-C
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number (self)"
}
mutating func adjust() {
self += 42
}
}
7.simpleDescription
extensions... like categories in Objective-C
Generics
func repeatString(item: String, times: Int) -> String[]
{
var result = String[]()
for i in 0..times {
result += item
}
return result
}
repeatString("knock", 4)
!
func repeatInt(item: Int, times: Int) -> Int[] {
var result = Int[]()
for i in 0..times {
result += item
}
return result
}
repeatInt(42, 4)
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)
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
But the most important feature, the only one
that you need to learn is...
Emoji!!!
A swift introduction to Swift
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.tearDown()
}
func testExample() {
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
self.measureBlock() {
}
}
}
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!")
}
}
}
}
}
}
And now...
Let's code
a Rpn Calculator
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
A swift introduction to Swift
A swift introduction to Swift
A swift introduction to Swift

More Related Content

What's hot

Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
 
Clean Architecture Applications in Python
Clean Architecture Applications in PythonClean Architecture Applications in Python
Clean Architecture Applications in PythonSubhash Bhushan
 
Boxing & unboxing
Boxing & unboxingBoxing & unboxing
Boxing & unboxingLarry Nung
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageCihad Horuzoğlu
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDSCVSSUT
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Introduction to the Dart language
Introduction to the Dart languageIntroduction to the Dart language
Introduction to the Dart languageJana Moudrá
 
Kotlin - scope functions and collections
Kotlin - scope functions and collectionsKotlin - scope functions and collections
Kotlin - scope functions and collectionsWei-Shen Lu
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersJiaxuan Lin
 

What's hot (20)

Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Clean Architecture Applications in Python
Clean Architecture Applications in PythonClean Architecture Applications in Python
Clean Architecture Applications in Python
 
Boxing & unboxing
Boxing & unboxingBoxing & unboxing
Boxing & unboxing
 
Full Stack Flutter Testing
Full Stack Flutter Testing Full Stack Flutter Testing
Full Stack Flutter Testing
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptx
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
C#.NET
C#.NETC#.NET
C#.NET
 
Support programmation orientée objet c# .net version f8
Support programmation orientée objet c#  .net version f8Support programmation orientée objet c#  .net version f8
Support programmation orientée objet c# .net version f8
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Introduction to the Dart language
Introduction to the Dart languageIntroduction to the Dart language
Introduction to the Dart language
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
 
Kotlin - scope functions and collections
Kotlin - scope functions and collectionsKotlin - scope functions and collections
Kotlin - scope functions and collections
 
XML Signature
XML SignatureXML Signature
XML Signature
 
What is Flutter
What is FlutterWhat is Flutter
What is Flutter
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for Beginners
 

Similar to A swift introduction to Swift

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objectsHusain Dalal
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresiMasters
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 

Similar to A swift introduction to Swift (20)

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Kotlin
KotlinKotlin
Kotlin
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan Soares
 
Monadologie
MonadologieMonadologie
Monadologie
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 

More from Giordano Scalzo

The Joy Of Server Side Swift Development
The Joy Of Server Side Swift DevelopmentThe Joy Of Server Side Swift Development
The Joy Of Server Side Swift DevelopmentGiordano Scalzo
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good codeGiordano Scalzo
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperGiordano Scalzo
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival GuideGiordano Scalzo
 
Better Software Developers
Better Software DevelopersBetter Software Developers
Better Software DevelopersGiordano Scalzo
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone DevelopmentGiordano Scalzo
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayGiordano Scalzo
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteGiordano Scalzo
 
10 minutes of me: Giordano Scalzo's Visual Resume
10 minutes of me: Giordano Scalzo's Visual Resume10 minutes of me: Giordano Scalzo's Visual Resume
10 minutes of me: Giordano Scalzo's Visual ResumeGiordano Scalzo
 

More from Giordano Scalzo (14)

The Joy Of Server Side Swift Development
The Joy Of Server Side Swift DevelopmentThe Joy Of Server Side Swift Development
The Joy Of Server Side Swift Development
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good code
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival Guide
 
Code kata
Code kataCode kata
Code kata
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
Better Software Developers
Better Software DevelopersBetter Software Developers
Better Software Developers
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infinite
 
10 minutes of me: Giordano Scalzo's Visual Resume
10 minutes of me: Giordano Scalzo's Visual Resume10 minutes of me: Giordano Scalzo's Visual Resume
10 minutes of me: Giordano Scalzo's Visual Resume
 
Scrum in an hour
Scrum in an hourScrum in an hour
Scrum in an hour
 

Recently uploaded

Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native BuildpacksVish Abrams
 
Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilVICTOR MAESTRE RAMIREZ
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdfMeon Technology
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampVICTOR MAESTRE RAMIREZ
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageDista
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptkinjal48
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxJoão Esperancinha
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyRaymond Okyere-Forson
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 

Recently uploaded (20)

Salesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptxSalesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptx
 
Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native Buildpacks
 
Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-Council
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdf
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - Datacamp
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.ppt
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptx
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human Beauty
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 

A swift introduction to Swift

  • 1. A swift introduction to Giordano Scalzo Closure Busker
  • 13. From
  • 14. To
  • 15. What does Swift look like?
  • 23. SHOW ME THE CODE!!!!!
  • 24. let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } teamScore
  • 25. ;
  • 26. ;
  • 28. var optionalName: String? = "John Appleseed" var greeting = "Hello!" ! if optionalName { greeting = "Hello, (optionalName!)" } Optional
  • 29. var optionalName: String? = "John Appleseed" var greeting = "Hello!" ! if let name = optionalName { greeting = "Hello, (name)" } Optional
  • 30. 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
  • 34. 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." }
  • 35. 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") }
  • 37. func greet(name: String, #day: String) -> String { return "Hello (name), today is (day)." } greet("Bob", day: "Wednesday") Named Parameters
  • 38. func greet(name: String, day: String) -> String { return "Hello (name), today is (day)." } greet("Bob", "Wednesday") Named Parameters Optional
  • 39. 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)")
  • 40. 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)")
  • 41. Functions are first class type
  • 42. 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
  • 43. 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)
  • 44. 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})
  • 45. 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
  • 46. 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
  • 47. Where are the classes?
  • 48. class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with (numberOfSides) sides." } }
  • 49. 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()
  • 50. 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()
  • 51. 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()
  • 52. class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 ... var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } ... } calculated properties
  • 53. class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } } observable properties
  • 54. 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
  • 55. 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
  • 56. like classes, but passed by value...in a smarter way
  • 57. classes are always passed by reference structs are passed by reference, but automatically copied when mutated
  • 58. Struct are used as ValueTypes, data components manipulated by classes
  • 60. 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
  • 61. enum ServerResponse { case Result(String, String) case Error(String) } Enumerations with a value associated
  • 62. Enumerations with a value associated let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.")
  • 63. 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)" }
  • 64. protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } Protocols... like Interface in Java or... protocols in Objective-C
  • 65. extension Int: ExampleProtocol { var simpleDescription: String { return "The number (self)" } mutating func adjust() { self += 42 } } 7.simpleDescription extensions... like categories in Objective-C
  • 67. func repeatString(item: String, times: Int) -> String[] { var result = String[]() for i in 0..times { result += item } return result } repeatString("knock", 4)
  • 68. ! func repeatInt(item: Int, times: Int) -> Int[] { var result = Int[]() for i in 0..times { result += item } return result } repeatInt(42, 4)
  • 69. 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)
  • 70. 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
  • 71. But the most important feature, the only one that you need to learn is...
  • 74. For me (imvho) the most useful new features are enumerations and pattern matching
  • 76. XCTest class RpnCalculatorKataTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testExample() { XCTAssert(true, "Pass") } func testPerformanceExample() { self.measureBlock() { } } }
  • 77. 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!") } } } } } }
  • 81. 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