49
Swift Study #2 #이상한모임 @신촌

Swift Study #2

Embed Size (px)

DESCRIPTION

Swift Study #2 정리자료 / #이상한모임 @신촌

Citation preview

Page 1: Swift Study #2

Swift Study #2#이상한모임 @신촌

Page 2: Swift Study #2

Collection Types

Page 3: Swift Study #2

Collection Types

• Arrays, Dictionary

• Typed Collections

• Generic Collections

Page 4: Swift Study #2

Mutability of Collections

• var = mutable, let = immutable

• let shoppingList = [“Eggs”, “Milk”] shoppingList[0] = [“Six Eggs”] b2: OK, b3: Error

Page 5: Swift Study #2

Arrays

• Array Type Shorthand Syntax

• Array<SomeType> -> SomeType[] //b2

• Array<SomeType> -> [SomeType] //b3

• var shoppingList: [String] = [“Eggs”, “Milk”]

Page 6: Swift Study #2

Accessing and Modifying an Array

• shoppingList.count

• shoppingList.isEmpty

• shoppingList.append(“Flour”)

• shoppingList += “Baking Powder”

• shoppingList += [“Chocolate Spread”, “Cheese”, “Butter”]

Page 7: Swift Study #2

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()

Page 8: Swift Study #2

Iterating Over an Array

• for item in shoppingList { println(item) }

• for (index, value) in enumerate(shoppingList) { println(“\(index+1): \(value)”) }

Page 9: Swift Study #2

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

Page 10: Swift Study #2

Dictionaries

• Dictionary<KeyType, ValueType> -> [KeyType: ValueType] //b3

• var airports: [String: String] = [“TYO”: “Tokyo”, “DUB”: “Dublin”]

Page 11: Swift Study #2

Accessing and Modifying a Dictionary

• airports.count

• airports[“LHR”] = “London”

• airports[“LHR”] = “London Heathrow”

Page 12: Swift Study #2

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”)}

Page 13: Swift Study #2

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”)}

Page 14: Swift Study #2

Iterating Over a Dictionary

• for (airportCode, airportName) in airports { println(“\(airportCode): \(airportName)”) }

• for airportCode in airports.keys

• for airportName in airports.values

Page 15: Swift Study #2

Creating an Empty Dictionary

• var namesOfIntegers = [Int: String]()namesOfIntegers[16] = “sixteen”namesOfIntegers = [:]

Page 16: Swift Study #2

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.

Page 17: Swift Study #2

Control Flow

Page 18: Swift Study #2

For-In

• for index in 1…5

• for _ in 1…10

• for item in names

• for (key, value) in json

• for character in “Hello”

Page 19: Swift Study #2

(Do-)While

• while condition { statements }

• do { statements } while condition

Page 20: Swift Study #2

Conditional Statements

• var temperatureInFahrenheit = 30 if temperatureInFahrenheit <= 32 { println(“It’s very cold. Consider wearing a scarf.”) }

Page 21: Swift Study #2

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.”) }

Page 22: Swift Study #2

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.”) }

Page 23: Swift Study #2

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.”) }

Page 24: Swift Study #2

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 }

Page 25: Swift Study #2

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

Page 26: Swift Study #2

No Implicit Fallthrough

• switch anotherCharacter { case “a”, “A”: println(“The letter A”) default: println(“Not the letter A”) }

• use the fallthrough keyword

Page 27: Swift Study #2

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” }

Page 28: Swift Study #2

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”) }

Page 29: Swift Study #2

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))”)}

Page 30: Swift Study #2

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”)}

Page 31: Swift Study #2

Control Transfer Statements

• continue

• break

• fallthrough

• return

Page 32: Swift Study #2

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.” }

Page 33: Swift Study #2

Labeled Statements

• Goto

• break, continue

Page 34: Swift Study #2

Functions

Page 35: Swift Study #2

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!”

Page 36: Swift Study #2

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)

Page 37: Swift Study #2

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”

Page 38: Swift Study #2

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”

Page 39: Swift Study #2

Shorthand External Parameter Names

• func containsCharacter(#string: String, #characterToFind: Character) -> Bool { // blah blah }

• let containsAVee = containsCharacter(string: “aardvark”, characterToFind: “v”)

Page 40: Swift Study #2

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”

Page 41: Swift Study #2

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”

Page 42: Swift Study #2

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)

Page 43: Swift Study #2

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, “-”)

Page 44: Swift Study #2

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)

Page 45: Swift Study #2

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”) }// () -> ()

Page 46: Swift Study #2

Using Function Types

• var mathFunction: (Int, Int) -> Int = addTwoIntsprintln(mathFunction(2,3))

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

• let anotherMathFunction = addTwoInts

Page 47: Swift Study #2

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”

Page 48: Swift Study #2

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 blahcurrentValue = moveNearerToZero(currentValue)

Page 49: Swift Study #2

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}