SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Downloaden Sie, um offline zu lesen
Swift Study #2
#이상한모임 @신촌
Collection Types
Collection Types
• Arrays, Dictionary
• Typed Collections
• Generic Collections
Mutability of
Collections
• var = mutable, let = immutable
• let shoppingList = [“Eggs”, “Milk”]

shoppingList[0] = [“Six Eggs”]



b2: OK, b3: Error
Arrays
• Array Type Shorthand Syntax
• Array<SomeType> -> SomeType[] //b2
• Array<SomeType> -> [SomeType] //b3
• var shoppingList: [String] =
[“Eggs”, “Milk”]
Accessing and
Modifying an Array
• shoppingList.count
• shoppingList.isEmpty
• shoppingList.append(“Flour”)
• shoppingList += “Baking Powder”
• shoppingList += [“Chocolate Spread”,
“Cheese”, “Butter”]
Accessing and
Modifying an Array
• shoppingList[0] = “Six Eggs”
• shoppingList[4…6] = [“Bananas”, “Apples”]
• shoppingList.insert(“Maple Syrup”,
atIndex: 0)
• let mapleSyrup =
shoppingList.removeAtIndex(0)
• let apples = shoppingList.removeLast()
Iterating Over an
Array
• for item in shoppingList {

println(item)

}
• for (index, value) in
enumerate(shoppingList) {

println(“(index+1): (value)”)

}
Creating and
Initializing an Array
• var someInts = [Int]()

someInts.append(3)

someInts = []
• var threeDoubles = [Double](count: 3,
repeatedValue: 0.0)
• var anotherThreeDoubles = Array(count: 3,
repeatedValue: 2.5)
• var sixDoubles = threeDoubles +
anotherThreeDoubles
Dictionaries
• Dictionary<KeyType, ValueType> ->
[KeyType: ValueType] //b3
• var airports: [String: String] =
[“TYO”: “Tokyo”, “DUB”: “Dublin”]
Accessing and
Modifying a Dictionary
• airports.count
• airports[“LHR”] = “London”
• airports[“LHR”] = “London Heathrow”
Accessing and
Modifying a Dictionary
• if let oldValue =
airports.updateValue(“Dublin
International”, forKey: “DUB”) {

println(oldValue)

}
• if let airportName = airports[“DUB”] {

println(airportName)

} else {

println(“not in the airports”)

}
Accessing and
Modifying a Dictionary
• airports[“APL”] = “Apple
International”

airports[“APL”] = nil
• if let removedValue =
airports.removeValueForKey(“DUB”) {

println(“removed (removedValue)”)

} else {

println(“not contain a value”)

}
Iterating Over a
Dictionary
• for (airportCode, airportName) in
airports {

println(“(airportCode): 
(airportName)”)

}
• for airportCode in airports.keys
• for airportName in airports.values
Creating an Empty
Dictionary
• var namesOfIntegers = [Int: String]()

namesOfIntegers[16] = “sixteen”

namesOfIntegers = [:]
Hash Values for
Dictionary Key Types
• A type must be hashable in order to
be used as a dictionary’s key type —
that is, the type must provide a way
to compute a hash value for itself.
Control Flow
For-In
• for index in 1…5
• for _ in 1…10
• for item in names
• for (key, value) in json
• for character in “Hello”
(Do-)While
• while condition {

statements

}
• do {

statements

} while condition
Conditional Statements
• var temperatureInFahrenheit = 30

if temperatureInFahrenheit <= 32 {

println(“It’s very cold.
Consider wearing a scarf.”)

}
Conditional Statements
• var temperatureInFahrenheit = 40

if temperatureInFahrenheit <= 32 {

println(“It’s very cold.
Consider wearing a scarf.”)

} else {

println(“It’s not that cold.
Wear a t-shirt.”)

}
Conditional Statements
• var temperatureInFahrenheit = 90

if temperatureInFahrenheit <= 32 {

println(“It’s very cold. Consider
wearing a scarf.”)

} else if temperatureInFahrenheit >= 86 {

println(“It’s really warm. Don’t
forget to wear sunscreen.”)

} else {

println(“It’s not that cold. Wear a
t-shirt.”)

}
Conditional Statements
• var temperatureInFahrenheit = 72

if temperatureInFahrenheit <= 32 {

println(“It’s very cold.
Consider wearing a scarf.”)

} else if temperatureInFahrenheit >=
86 {

println(“It’s really warm. Don’t
forget to wear sunscreen.”)

}
Switch
• switch some value to consider {

case value 1:

respond to value 1

case value 2,

value 3:

respond to value 2 or 3

default:

otherwise, do something else

}
No Implicit
Fallthrough
• switch anotherCharacter {

case “a”:

case “A”:

println(“The letter A”)

default:

println(“Not the letter A”)

}

// this will report a compile-time
error
No Implicit
Fallthrough
• switch anotherCharacter {

case “a”, “A”:

println(“The letter A”)

default:

println(“Not the letter A”)

}
• use the fallthrough keyword
Range Matching
• switch count {

case 0:

naturalCount = “no”

case 1…3:

naturalCount = “a few”

case 4…9:

naturalCount = “several”

case 10…99:

naturalCount = “tens of”

case 100…999:

naturalCount = “hundreds of”

case 1000…999_999:

naturalCount = “thousands of”

default:

naturalCount = “millions and millions of”

}
Tuples
• let somePoint = (1,1)

switch somePoint {

case (0,0):

println(“at the origin”)

case (_,0):

println(“on the x-axis”)

case (0,_):

println(“on the y-axis”)

case (-2…2,-2…2):

println(“inside the box”)

default:

println(“outside of the box”)

}
Value Bindings
• var anotherPoint = (2,0)

switch anotherPoint {

case (let x, 0):

println(“on the x-axis an x value of 
(x)”)

case (0, let y):

println(“on the y-axis an y value of 
(y)”)

case let (x,y):

println(“somewhere else at ((x), 
(y))”)

}
Where
• let yetAnotherPoint = (1,-1)

switch yetAnotherPoint {

case let (x,y) where x == y:

println(“on the line x == y”)

case let (x,y) where x == -y:

println(“on the line x == -y”)

case let (x,y):

println(“just some arbitrary
point”)

}
Control Transfer
Statements
• continue
• break
• fallthrough
• return
Fallthrough
• let integerToDescribe = 5

switch integerToDescribe {

case 2,3,5,7,11,13,17,19:

description += " a prime number,
and also”

fallthrough

default:

description += “ an integer.”

}
Labeled Statements
• Goto
• break, continue
Functions
Defining and Calling
Functions
• func sayHello(personName: String) ->
String {

let greeting = “Hello, ” +
personName + “!”

return greeting

}



println(sayHello(“Anna”))

// prints “Hello, Anna!”

println(sayHello(“Brian”))

// prints “Hello, Brian!”
Function Parameters
and Return Values
• Multiple Input Parameters
• func halfOpenRangeLength(start: Int, end: Int) ->
Int
• Functions Without Parameters
• func sayHelloWorld() -> String
• Functions Without Return Values
• func sayGoodbye(personName: String)
• Functions with Multiple Return Values
• return (vowels, consonants, others)
Function Parameter
Names
• External Parameter Names
• func join(s1: String, s2: String,
joiner: String) -> String {

return s1 + joiner + s2

}
• join(“hello”, “world”, “, ”)

// returns “hello, world”
Function Parameter
Names
• External Parameter Names
• func join(string s1: String, toString
s2: String, withJoiner joiner:
String) -> String {

return s1 + joiner + s2

}
• join(string: “hello”, toString:
“world”, withJoiner: “, ”)

// returns “hello, world”
Shorthand External
Parameter Names
• func containsCharacter(#string:
String, #characterToFind: Character)
-> Bool { // blah blah }
• let containsAVee =
containsCharacter(string:
“aardvark”, characterToFind: “v”)
Default Parameter
Values
• func join(string s1: String, toString s2:
String, withJoiner joiner: String = “ ”) -
> String {

return s1 + joiner + s2

}
• join(string: “hello”, toString: “world”,
withJoiner: “-”)

// returns “hello-world”
• join(string: “hello”, toString: “world”)

// returns “hello world”
External Names for Parameters
with Default Values
• func join(s1: String, s2: String,
joiner: String = “ ”) -> String {

return s1 + joiner + s2

}
• join(“hello”,“world”, joiner: “-”)

// returns “hello-world”
Variadic Parameters
• func arithmeticMean(numbers: Double…) -
> Double {

var total: Double = 0

for number in numbers {

total += number

}

return total / Double(number.count)

}



arithmeticMean(1, 2, 3, 4, 5)

arithmeticMean(3, 8, 19)
Constant and Variable
Parameters
• func alignRight(var string: String, count: Int, pad:
Character) -> String {

let amountToPad = count - countElements(string)

if amountToPad < 1 {

return string

}

for _ in 1…amountToPad {

string += pad + string

}

return string

}



let originalString = “hello”

let paddedString = alignRight(originalString, 10, “-”)
In-Out Parameters
• func swapTwoInts(inout a: Int, inout
b: Int) {

let temporaryA = a

a = b

b = temporaryA

}



var someInt = 3

var anotherInt = 107

swapTwoInts(&someInt, &anotherInt)
Function Types
• func addTwoInts(a: Int, b: Int) ->
Int { return a + b }

func multiplyTwoInts(a: Int, b: Int)
-> Int { return a * b }

// (Int, Int) -> Int
• func printHelloWorld() {

println(“hello, world”)

}

// () -> ()
Using Function Types
• var mathFunction: (Int, Int) -> Int
= addTwoInts

println(mathFunction(2,3))
• mathFunction = multiplyTwoInts

println(mathFunction(2,3))
• let anotherMathFunction = addTwoInts
Function Types as
Parameter Types
• func printMathResult(mathFunction:
(Int, Int) -> Int, a: Int, b: Int) {

println(“Result: 
(mathFunction(a,b))”)

}



printMathResult(addTwoInts,3,5)

// prints “Result: 8”
Function Types as
Return Types
• func stepForward(input: Int) -> Int {

return input + 1

}

func stepBackward(input: Int) -> Int {

return input - 1

}



func chooseStepFunction(backwards: Bool) -> (Int) -> Int {

return backwards ? stepBackward : stepForward

}



let moveNearerToZero = chooseStepFunction(currentValue > 0)

// blah blah

currentValue = moveNearerToZero(currentValue)

Nested Functions
• func chooseStepFunction(backward:
Bool) -> (Int) -> Int {

func stepForward(input: Int) ->
Int { return input + 1 }

func stepBackward(input: Int) ->
Int { return input - 1 }

return backwards ? stepBackward:
stepForward

}

Weitere ähnliche Inhalte

Was ist angesagt?

λ | Lenses
λ | Lensesλ | Lenses
λ | LensesOpen-IT
 
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingGareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingYury Chemerkin
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)진성 오
 
Py Die R E A D M E
Py Die  R E A D M EPy Die  R E A D M E
Py Die R E A D M Ecfministries
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kirill Rozov
 
The Ring programming language version 1.9 book - Part 31 of 210
The Ring programming language version 1.9 book - Part 31 of 210The Ring programming language version 1.9 book - Part 31 of 210
The Ring programming language version 1.9 book - Part 31 of 210Mahmoud Samir Fayed
 
2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control 2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control kinan keshkeh
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189Mahmoud Samir Fayed
 

Was ist angesagt? (20)

P2 2017 python_strings
P2 2017 python_stringsP2 2017 python_strings
P2 2017 python_strings
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingGareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
 
P3 2017 python_regexes
P3 2017 python_regexesP3 2017 python_regexes
P3 2017 python_regexes
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
2017 biological databasespart2
2017 biological databasespart22017 biological databasespart2
2017 biological databasespart2
 
Py Die R E A D M E
Py Die  R E A D M EPy Die  R E A D M E
Py Die R E A D M E
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
R for you
R for youR for you
R for you
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
The Ring programming language version 1.9 book - Part 31 of 210
The Ring programming language version 1.9 book - Part 31 of 210The Ring programming language version 1.9 book - Part 31 of 210
The Ring programming language version 1.9 book - Part 31 of 210
 
2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control 2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 

Ähnlich wie Swift Collection Types and Control Flow

Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldWerner Hofstra
 
Mcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singhMcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singhDIVYA SINGH
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Iterators, Hashes, and Arrays
Iterators, Hashes, and ArraysIterators, Hashes, and Arrays
Iterators, Hashes, and ArraysBlazing Cloud
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreWeb Zhao
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181Mahmoud Samir Fayed
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Empathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeEmpathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeMario Gleichmann
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsYashJain47002
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapHoward Lewis Ship
 
Python WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorPython WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorAmy Hanlon
 
The Ring programming language version 1.2 book - Part 14 of 84
The Ring programming language version 1.2 book - Part 14 of 84The Ring programming language version 1.2 book - Part 14 of 84
The Ring programming language version 1.2 book - Part 14 of 84Mahmoud Samir Fayed
 
【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽
【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽
【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽tbosstraining
 
The Ring programming language version 1.5.1 book - Part 23 of 180
The Ring programming language version 1.5.1 book - Part 23 of 180The Ring programming language version 1.5.1 book - Part 23 of 180
The Ring programming language version 1.5.1 book - Part 23 of 180Mahmoud Samir Fayed
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyGautam Rege
 

Ähnlich wie Swift Collection Types and Control Flow (20)

P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Mcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singhMcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singh
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Iterators, Hashes, and Arrays
Iterators, Hashes, and ArraysIterators, Hashes, and Arrays
Iterators, Hashes, and Arrays
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Empathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible codeEmpathic Programming - How to write comprehensible code
Empathic Programming - How to write comprehensible code
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 
Python WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorPython WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd Behavior
 
The Ring programming language version 1.2 book - Part 14 of 84
The Ring programming language version 1.2 book - Part 14 of 84The Ring programming language version 1.2 book - Part 14 of 84
The Ring programming language version 1.2 book - Part 14 of 84
 
【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽
【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽
【第一季第三期】Thinking in Javascript & OO in Javascript - 清羽
 
The Ring programming language version 1.5.1 book - Part 23 of 180
The Ring programming language version 1.5.1 book - Part 23 of 180The Ring programming language version 1.5.1 book - Part 23 of 180
The Ring programming language version 1.5.1 book - Part 23 of 180
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of ruby
 

Kürzlich hochgeladen

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 

Kürzlich hochgeladen (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 

Swift Collection Types and Control Flow

  • 3. Collection Types • Arrays, Dictionary • Typed Collections • Generic Collections
  • 4. Mutability of Collections • var = mutable, let = immutable • let shoppingList = [“Eggs”, “Milk”]
 shoppingList[0] = [“Six Eggs”]
 
 b2: OK, b3: Error
  • 5. Arrays • Array Type Shorthand Syntax • Array<SomeType> -> SomeType[] //b2 • Array<SomeType> -> [SomeType] //b3 • var shoppingList: [String] = [“Eggs”, “Milk”]
  • 6. Accessing and Modifying an Array • shoppingList.count • shoppingList.isEmpty • shoppingList.append(“Flour”) • shoppingList += “Baking Powder” • shoppingList += [“Chocolate Spread”, “Cheese”, “Butter”]
  • 7. Accessing and Modifying an Array • shoppingList[0] = “Six Eggs” • shoppingList[4…6] = [“Bananas”, “Apples”] • shoppingList.insert(“Maple Syrup”, atIndex: 0) • let mapleSyrup = shoppingList.removeAtIndex(0) • let apples = shoppingList.removeLast()
  • 8. Iterating Over an Array • for item in shoppingList {
 println(item)
 } • for (index, value) in enumerate(shoppingList) {
 println(“(index+1): (value)”)
 }
  • 9. Creating and Initializing an Array • var someInts = [Int]()
 someInts.append(3)
 someInts = [] • var threeDoubles = [Double](count: 3, repeatedValue: 0.0) • var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5) • var sixDoubles = threeDoubles + anotherThreeDoubles
  • 10. Dictionaries • Dictionary<KeyType, ValueType> -> [KeyType: ValueType] //b3 • var airports: [String: String] = [“TYO”: “Tokyo”, “DUB”: “Dublin”]
  • 11. Accessing and Modifying a Dictionary • airports.count • airports[“LHR”] = “London” • airports[“LHR”] = “London Heathrow”
  • 12. Accessing and Modifying a Dictionary • if let oldValue = airports.updateValue(“Dublin International”, forKey: “DUB”) {
 println(oldValue)
 } • if let airportName = airports[“DUB”] {
 println(airportName)
 } else {
 println(“not in the airports”)
 }
  • 13. Accessing and Modifying a Dictionary • airports[“APL”] = “Apple International”
 airports[“APL”] = nil • if let removedValue = airports.removeValueForKey(“DUB”) {
 println(“removed (removedValue)”)
 } else {
 println(“not contain a value”)
 }
  • 14. Iterating Over a Dictionary • for (airportCode, airportName) in airports {
 println(“(airportCode): (airportName)”)
 } • for airportCode in airports.keys • for airportName in airports.values
  • 15. Creating an Empty Dictionary • var namesOfIntegers = [Int: String]()
 namesOfIntegers[16] = “sixteen”
 namesOfIntegers = [:]
  • 16. Hash Values for Dictionary Key Types • A type must be hashable in order to be used as a dictionary’s key type — that is, the type must provide a way to compute a hash value for itself.
  • 18. For-In • for index in 1…5 • for _ in 1…10 • for item in names • for (key, value) in json • for character in “Hello”
  • 19. (Do-)While • while condition {
 statements
 } • do {
 statements
 } while condition
  • 20. Conditional Statements • var temperatureInFahrenheit = 30
 if temperatureInFahrenheit <= 32 {
 println(“It’s very cold. Consider wearing a scarf.”)
 }
  • 21. Conditional Statements • var temperatureInFahrenheit = 40
 if temperatureInFahrenheit <= 32 {
 println(“It’s very cold. Consider wearing a scarf.”)
 } else {
 println(“It’s not that cold. Wear a t-shirt.”)
 }
  • 22. Conditional Statements • var temperatureInFahrenheit = 90
 if temperatureInFahrenheit <= 32 {
 println(“It’s very cold. Consider wearing a scarf.”)
 } else if temperatureInFahrenheit >= 86 {
 println(“It’s really warm. Don’t forget to wear sunscreen.”)
 } else {
 println(“It’s not that cold. Wear a t-shirt.”)
 }
  • 23. Conditional Statements • var temperatureInFahrenheit = 72
 if temperatureInFahrenheit <= 32 {
 println(“It’s very cold. Consider wearing a scarf.”)
 } else if temperatureInFahrenheit >= 86 {
 println(“It’s really warm. Don’t forget to wear sunscreen.”)
 }
  • 24. Switch • switch some value to consider {
 case value 1:
 respond to value 1
 case value 2,
 value 3:
 respond to value 2 or 3
 default:
 otherwise, do something else
 }
  • 25. No Implicit Fallthrough • switch anotherCharacter {
 case “a”:
 case “A”:
 println(“The letter A”)
 default:
 println(“Not the letter A”)
 }
 // this will report a compile-time error
  • 26. No Implicit Fallthrough • switch anotherCharacter {
 case “a”, “A”:
 println(“The letter A”)
 default:
 println(“Not the letter A”)
 } • use the fallthrough keyword
  • 27. Range Matching • switch count {
 case 0:
 naturalCount = “no”
 case 1…3:
 naturalCount = “a few”
 case 4…9:
 naturalCount = “several”
 case 10…99:
 naturalCount = “tens of”
 case 100…999:
 naturalCount = “hundreds of”
 case 1000…999_999:
 naturalCount = “thousands of”
 default:
 naturalCount = “millions and millions of”
 }
  • 28. Tuples • let somePoint = (1,1)
 switch somePoint {
 case (0,0):
 println(“at the origin”)
 case (_,0):
 println(“on the x-axis”)
 case (0,_):
 println(“on the y-axis”)
 case (-2…2,-2…2):
 println(“inside the box”)
 default:
 println(“outside of the box”)
 }
  • 29. Value Bindings • var anotherPoint = (2,0)
 switch anotherPoint {
 case (let x, 0):
 println(“on the x-axis an x value of (x)”)
 case (0, let y):
 println(“on the y-axis an y value of (y)”)
 case let (x,y):
 println(“somewhere else at ((x), (y))”)
 }
  • 30. Where • let yetAnotherPoint = (1,-1)
 switch yetAnotherPoint {
 case let (x,y) where x == y:
 println(“on the line x == y”)
 case let (x,y) where x == -y:
 println(“on the line x == -y”)
 case let (x,y):
 println(“just some arbitrary point”)
 }
  • 31. Control Transfer Statements • continue • break • fallthrough • return
  • 32. Fallthrough • let integerToDescribe = 5
 switch integerToDescribe {
 case 2,3,5,7,11,13,17,19:
 description += " a prime number, and also”
 fallthrough
 default:
 description += “ an integer.”
 }
  • 35. Defining and Calling Functions • func sayHello(personName: String) -> String {
 let greeting = “Hello, ” + personName + “!”
 return greeting
 }
 
 println(sayHello(“Anna”))
 // prints “Hello, Anna!”
 println(sayHello(“Brian”))
 // prints “Hello, Brian!”
  • 36. Function Parameters and Return Values • Multiple Input Parameters • func halfOpenRangeLength(start: Int, end: Int) -> Int • Functions Without Parameters • func sayHelloWorld() -> String • Functions Without Return Values • func sayGoodbye(personName: String) • Functions with Multiple Return Values • return (vowels, consonants, others)
  • 37. Function Parameter Names • External Parameter Names • func join(s1: String, s2: String, joiner: String) -> String {
 return s1 + joiner + s2
 } • join(“hello”, “world”, “, ”)
 // returns “hello, world”
  • 38. Function Parameter Names • External Parameter Names • func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String {
 return s1 + joiner + s2
 } • join(string: “hello”, toString: “world”, withJoiner: “, ”)
 // returns “hello, world”
  • 39. Shorthand External Parameter Names • func containsCharacter(#string: String, #characterToFind: Character) -> Bool { // blah blah } • let containsAVee = containsCharacter(string: “aardvark”, characterToFind: “v”)
  • 40. Default Parameter Values • func join(string s1: String, toString s2: String, withJoiner joiner: String = “ ”) - > String {
 return s1 + joiner + s2
 } • join(string: “hello”, toString: “world”, withJoiner: “-”)
 // returns “hello-world” • join(string: “hello”, toString: “world”)
 // returns “hello world”
  • 41. External Names for Parameters with Default Values • func join(s1: String, s2: String, joiner: String = “ ”) -> String {
 return s1 + joiner + s2
 } • join(“hello”,“world”, joiner: “-”)
 // returns “hello-world”
  • 42. Variadic Parameters • func arithmeticMean(numbers: Double…) - > Double {
 var total: Double = 0
 for number in numbers {
 total += number
 }
 return total / Double(number.count)
 }
 
 arithmeticMean(1, 2, 3, 4, 5)
 arithmeticMean(3, 8, 19)
  • 43. Constant and Variable Parameters • func alignRight(var string: String, count: Int, pad: Character) -> String {
 let amountToPad = count - countElements(string)
 if amountToPad < 1 {
 return string
 }
 for _ in 1…amountToPad {
 string += pad + string
 }
 return string
 }
 
 let originalString = “hello”
 let paddedString = alignRight(originalString, 10, “-”)
  • 44. In-Out Parameters • func swapTwoInts(inout a: Int, inout b: Int) {
 let temporaryA = a
 a = b
 b = temporaryA
 }
 
 var someInt = 3
 var anotherInt = 107
 swapTwoInts(&someInt, &anotherInt)
  • 45. Function Types • func addTwoInts(a: Int, b: Int) -> Int { return a + b }
 func multiplyTwoInts(a: Int, b: Int) -> Int { return a * b }
 // (Int, Int) -> Int • func printHelloWorld() {
 println(“hello, world”)
 }
 // () -> ()
  • 46. Using Function Types • var mathFunction: (Int, Int) -> Int = addTwoInts
 println(mathFunction(2,3)) • mathFunction = multiplyTwoInts
 println(mathFunction(2,3)) • let anotherMathFunction = addTwoInts
  • 47. Function Types as Parameter Types • func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
 println(“Result: (mathFunction(a,b))”)
 }
 
 printMathResult(addTwoInts,3,5)
 // prints “Result: 8”
  • 48. Function Types as Return Types • func stepForward(input: Int) -> Int {
 return input + 1
 }
 func stepBackward(input: Int) -> Int {
 return input - 1
 }
 
 func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
 return backwards ? stepBackward : stepForward
 }
 
 let moveNearerToZero = chooseStepFunction(currentValue > 0)
 // blah blah
 currentValue = moveNearerToZero(currentValue)

  • 49. Nested Functions • func chooseStepFunction(backward: Bool) -> (Int) -> Int {
 func stepForward(input: Int) -> Int { return input + 1 }
 func stepBackward(input: Int) -> Int { return input - 1 }
 return backwards ? stepBackward: stepForward
 }