SlideShare ist ein Scribd-Unternehmen logo
1 von 84
Downloaden Sie, um offline zu lesen
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 += 3
} else {
teamScore += 1
}
}
teamScore
;
;
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
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!!!
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
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
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Modules in AngularJs
Modules in AngularJsModules in AngularJs
Modules in AngularJs
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Practical Groovy DSL
Practical Groovy DSLPractical Groovy DSL
Practical Groovy DSL
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
Automation With Appium
Automation With AppiumAutomation With Appium
Automation With Appium
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 

Kürzlich hochgeladen (20)

Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 

A swift introduction to Swift

  • 1. A swift introduction to Giordano Scalzo Closure Busker
  • 3.
  • 4.
  • 6.
  • 7.
  • 8.
  • 10.
  • 11.
  • 12.
  • 13. From
  • 14. To
  • 15. What does Swift look like?
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 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. ;
  • 27.
  • 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
  • 32.
  • 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...
  • 73.
  • 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