diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..292eeff Binary files /dev/null and b/.DS_Store differ diff --git a/Lab - Classes.playground/Pages/1. Exercise - Define a Base Class.xcplaygroundpage/Contents.swift b/Lab - Classes.playground/Pages/1. Exercise - Define a Base Class.xcplaygroundpage/Contents.swift index 8576732..26ccb5a 100644 --- a/Lab - Classes.playground/Pages/1. Exercise - Define a Base Class.xcplaygroundpage/Contents.swift +++ b/Lab - Classes.playground/Pages/1. Exercise - Define a Base Class.xcplaygroundpage/Contents.swift @@ -5,21 +5,47 @@ Create a `Spaceship` class with three variable properties: `name`, `health`, and `position`. The default value of `name` should be an empty string and `health` should be 0. `position` will be represented by an `Int` where negative numbers place the ship further to the left and positive numbers place the ship further to the right. The default value of `position` should be 0. */ - +class Spaceship { + var name: String = "" + var health = 0 + var position = 0 + + func moveLeft() { + self.position -= 1 + } + + func moveRight() { + self.position += 1 + } + + func wasHit() { + self.health -= 5 + if health <= 0 { + + print("Sorry. Your ship was hit one too many times. Do you want to play again?") + } + } +} /*: Create a `let` constant called `falcon` and assign it to an instance of `Spaceship`. After initialization, set `name` to "Falcon". */ - +let falcon = Spaceship() +falcon.name = "Falcon" /*: Go back and add a method called `moveLeft()` to the definition of `Spaceship`. This method should adjust the position of the spaceship to the left by one. Add a similar method called `moveRight()` that moves the spaceship to the right. Once these methods exist, use them to move `falcon` to the left twice and to the right once. Print the new position of `falcon` after each change in position. */ - - +falcon.moveLeft() +print("The new posistion of \(falcon.name) is \(falcon.position)") +falcon.moveLeft() +print("The new posistion of \(falcon.name) is \(falcon.position)") +falcon.moveRight() +print("The new posistion of \(falcon.name) is \(falcon.position)") /*: The last thing `Spaceship` needs for this example is a method to handle what happens if the ship gets hit. Go back and add a method `wasHit()` to `Spaceship` that will decrement the ship's health by 5, then if `health` is less than or equal to 0 will print "Sorry. Your ship was hit one too many times. Do you want to play again?" Once this method exists, call it on `falcon` and print out the value of `health`. */ +falcon.wasHit() //: page 1 of 4 | [Next: Exercise - Create a Subclass](@next) diff --git a/Lab - Classes.playground/Pages/2. Exercise - Create a Subclass.xcplaygroundpage/Contents.swift b/Lab - Classes.playground/Pages/2. Exercise - Create a Subclass.xcplaygroundpage/Contents.swift index 69a1117..236376e 100644 --- a/Lab - Classes.playground/Pages/2. Exercise - Create a Subclass.xcplaygroundpage/Contents.swift +++ b/Lab - Classes.playground/Pages/2. Exercise - Create a Subclass.xcplaygroundpage/Contents.swift @@ -26,21 +26,58 @@ class Spaceship { /*: Define a new class `Fighter` that inherits from `Spaceship`. Add a variable property `weapon` that defaults to an empty string and a variable property `remainingFirePower` that defaults to 5. */ - +class Fighter: Spaceship { + var weapon : String = "" + var remainingFirePower = 5 + + func fire(){ + if remainingFirePower > 0 { + remainingFirePower -= 1 + } else { + print ("You have no more fire power.") + } + } +} /*: Create a new instance of `Fighter` called `destroyer`. A `Fighter` will be able to shoot incoming objects to avoid colliding with them. After initialization, set `weapon` to "Laser" and `remainingFirePower` to 10. Note that since `Fighter` inherits from `Spaceship`, it also has properties for `name`, `health`, and `position`, and has methods for `moveLeft()`, `moveRight()`, and `wasHit()` even though you did not specifically add them to the declaration of `Fighter`. Knowing that, set `name` to "Destroyer," print `position`, then call `moveRight()` and print `position` again. */ - +let destroyer = Fighter() +destroyer.weapon = "Laser" +destroyer.remainingFirePower = 10 +destroyer.name = "Destroyer" +print("The position of \(destroyer.name) is \(destroyer.position)") +destroyer.moveRight() +print("The position of \(destroyer.name) is \(destroyer.position)") /*: Try to print `weapon` on `falcon`. Why doesn't this work? Provide your answer in a comment or a print statement below, and remove any code you added that doesn't compile. */ - +// print(falcon.weapon) It doesn't work because falcon hasn't a property named "weapon". This property is in a subclass only /*: Add a method to `fighter` called `fire()`. This should check to see if `remainingFirePower` is greater than 0, and if so, should decrement `remainingFirePower` by one. If `remainingFirePower` is not greater than 0, print "You have no more fire power." Call `fire()` on `destroyer` a few times and print `remainingFirePower` after each method call. */ - - +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") +destroyer.fire() +print("You have more \(destroyer.remainingFirePower) power") //: [Previous](@previous) | page 2 of 4 | [Next: Exercise - Override Methods and Properties](@next) diff --git a/Lab - Classes.playground/Pages/3. Exercise - Override Methods and Properties.xcplaygroundpage/Contents.swift b/Lab - Classes.playground/Pages/3. Exercise - Override Methods and Properties.xcplaygroundpage/Contents.swift index a25449d..b1fbc89 100644 --- a/Lab - Classes.playground/Pages/3. Exercise - Override Methods and Properties.xcplaygroundpage/Contents.swift +++ b/Lab - Classes.playground/Pages/3. Exercise - Override Methods and Properties.xcplaygroundpage/Contents.swift @@ -39,8 +39,21 @@ class Fighter: Spaceship { /*: Define a new class `ShieldedShip` that inherits from `Fighter`. Add a variable property `shieldStrength` that defaults to 25. Create a new instance of `ShieldedShip` called `defender`. Set `name` to "Defender" and `weapon` to "Cannon." Call `moveRight()` and print `position`, then call `fire()` and print `remainingFirePower`. */ - +class ShieldedShip : Fighter { + var shieldStrength = 25 + +} + +let defender = ShieldedShip() +defender.name = "Defender" +defender.weapon = "Cannon" +defender.moveRight() +defender.fire() +print("The position of \(defender.name) is \(defender.position) ") +defender.fire() +defender.fire() +print("\(defender.name) has \(defender.remainingFirePower) more power") /*: Go back to your declaration of `ShieldedShip` and override `wasHit()`. In the body of the method, check to see if `shieldStrength` is greater than 0. If it is, decrement `shieldStrength` by 5. Otherwise, decrement `health` by 5. Call `wasHit()` on `defender` and print `shieldStrength` and `health`. */ diff --git a/Lab - Classes.playground/Pages/4. Exercise - Class Memberwise Initializers and References.xcplaygroundpage/Contents.swift b/Lab - Classes.playground/Pages/4. Exercise - Class Memberwise Initializers and References.xcplaygroundpage/Contents.swift index a8e5b19..cf61a76 100644 --- a/Lab - Classes.playground/Pages/4. Exercise - Class Memberwise Initializers and References.xcplaygroundpage/Contents.swift +++ b/Lab - Classes.playground/Pages/4. Exercise - Class Memberwise Initializers and References.xcplaygroundpage/Contents.swift @@ -7,6 +7,12 @@ class Spaceship { let name: String var health: Int var position: Int + + init(name: String, health: Int, position: Int){ + self.name = name + self.health = health + self.position = position + } func moveLeft() { position -= 1 @@ -27,6 +33,12 @@ class Spaceship { class Fighter: Spaceship { let weapon: String var remainingFirePower: Int + + init(weapon: String, remainingFirePower: Int, name: String, health:Int, position:Int ){ + self.weapon = weapon + self.remainingFirePower = remainingFirePower + super.init(name: name, health: health, position: position) + } func fire() { if remainingFirePower > 0 { @@ -40,6 +52,11 @@ class Fighter: Spaceship { class ShieldedShip: Fighter { var shieldStrength: Int + + init(shieldStrength: Int,weapon: String, remainingFirePower: Int, name: String, health:Int, position:Int ){ + self.shieldStrength = shieldStrength + super.init(weapon: weapon, remainingFirePower: remainingFirePower, name: name, health: health, position: position) + } override func wasHit() { if shieldStrength > 0 { shieldStrength -= 5 @@ -53,27 +70,31 @@ class ShieldedShip: Fighter { Then create an instance of `Spaceship` below called `falcon`. Use the memberwise initializer you just created. The ship's name should be "Falcon." */ - +let falcon = Spaceship(name: "Falcon", health: 0, position: 0) /*: Writing initializers for subclasses can get tricky. Your initializer needs to not only set the properties declared on the subclass, but also set all of the uninitialized properties on classes that it inherits from. Go to the declaration of `Fighter` and write an initializer that takes an argument for each property on `Fighter` and for each property on `Spaceship`. Set the properties accordingly. (Hint: you can call through to a superclass' initializer with `super.init` *after* you initialize all of the properties on the subclass). Then create an instance of `Fighter` below called `destroyer`. Use the memberwise initializer you just created. The ship's name should be "Destroyer." */ - +let destroyer = Fighter(weapon: "???", remainingFirePower: 100, name: "Destroyer", health: 100, position: 0) /*: Now go add an initializer to `ShieldedShip` that takes an argument for each property on `ShieldedShip`, `Fighter`, and `Spaceship`, and sets the properties accordingly. Remember that you can call through to the initializer on `Fighter` using `super.init`. Then create an instance of `ShieldedShip` below called `defender`. Use the memberwise initializer you just created. The ship's name should be "Defender." */ - +let defender = ShieldedShip(shieldStrength: 100, weapon: "???", remainingFirePower: 100, name: "Defender", health: 100, position: 0) /*: Create a new constant named `sameShip` and set it equal to `falcon`. Print out the position of `sameShip` and `falcon`, then call `moveLeft()` on `sameShip` and print out the position of `sameShip` and `falcon` again. Did both positions change? Why? If both were structs instead of classes, would it be the same? Why or why not? Provide your answer in a comment or print statement below. */ - - +let sameShip = falcon +print ("The position of \(falcon.name) is \(falcon.position)") +print ("The position of \(sameShip.name) is \(sameShip.position)") +sameShip.moveLeft() +print ("The position of \(falcon.name) is \(falcon.position)") +print ("The position of \(sameShip.name) is \(sameShip.position)") // is the same position because they are classes!!! No Structs /*: _Copyright © 2018 Apple Inc._ diff --git a/Lab - Collections.playground/Pages/1. Exercise - Arrays.xcplaygroundpage/Contents.swift b/Lab - Collections.playground/Pages/1. Exercise - Arrays.xcplaygroundpage/Contents.swift index fbcf943..fe9b16f 100644 --- a/Lab - Collections.playground/Pages/1. Exercise - Arrays.xcplaygroundpage/Contents.swift +++ b/Lab - Collections.playground/Pages/1. Exercise - Arrays.xcplaygroundpage/Contents.swift @@ -3,31 +3,36 @@ Assume you are an event coordinator for a community charity event and are keeping a list of who has registered. Create a variable `registrationList` that will hold strings. It should be empty after initialization. */ - - +var registrationList: [String] = [] /*: Your friend Sara is the first to register for the event. Add her name to `registrationList` using the `append(_:)` method. Print the contents of the collection. */ - +registrationList.append("Sara") +print(registrationList) /*: Add four additional names into the array using the `+=` operator. All of the names should be added in one step. Print the contents of the collection. */ - +registrationList += ["Mario", "Luca","Giorgia","Lucia"] +print(registrationList) /*: Use the `insert(_:at:)` method to add `Charlie` into the array as the second element. Print the contents of the collection. */ - +registrationList.insert("Charlie", at: 1) +print(registrationList) /*: Someone had a conflict and decided to transfer her registration to someone else. Use array subscripting to change the sixth element to `Rebecca`. Print the contents of the collection. */ +registrationList[5] = "Rebecca" +print(registrationList) /*: Call `removeLast()` on `registrationList`. If done correctly, this should remove `Rebecca` from the collection. Store the result of `removeLast()` into a new constant `deletedItem`, then print `deletedItem`. */ - +let deleteItem = registrationList.removeLast() +print(deleteItem) //: page 1 of 4 | [Next: App Exercise - Activity Challenge](@next) diff --git a/Lab - Collections.playground/Pages/2. App Exercise - Activity Challenge.xcplaygroundpage/Contents.swift b/Lab - Collections.playground/Pages/2. App Exercise - Activity Challenge.xcplaygroundpage/Contents.swift index d9e7443..d3ada9d 100644 --- a/Lab - Collections.playground/Pages/2. App Exercise - Activity Challenge.xcplaygroundpage/Contents.swift +++ b/Lab - Collections.playground/Pages/2. App Exercise - Activity Challenge.xcplaygroundpage/Contents.swift @@ -7,26 +7,35 @@ Using arrays of type `String`, create at least two lists, one for walking challenges, and one for running challenges. Each should have at least two challenges and should be initialized using an array literal. Feel free to create more lists for different activities. */ - +var walkingChallenges: [String] = ["Walk 3 miles a day","Walk 5 miles a day","Walk 10 miles a day"] +var runningChallenges: [String] = ["Run 1 times a week", "Run 3 times a week","Run 5 times a week"] /*: In your app you want to show all of these lists on the same screen grouped into sections. Create a `challenges` array that holds each of the lists you have created (it will be an array of arrays). Using `challenges`, print the first element in the second challenge list. */ - +var challenges = [walkingChallenges,runningChallenges] +print(challenges[1][0]) /*: All of the challenges will reset at the end of the month. Use the `removeAll` to remove everything from `challenges`. Print `challenges`. */ - +challenges.removeAll() +print(challenges) /*: Create a new array of type `String` that will represent challenges a user has committed to instead of available challenges. It can be an empty array or have a few items in it. */ - +var userChallenges: [String] = [] /*: Write an if statement that will use `isEmpty` to check if there is anything in the array. If there is not, print a statement asking the user to commit to a challenge. Add an else-if statement that will print "The challenge you have chosen is " if the array count is exactly 1. Then add an else statement that will print "You have chosen multiple challenges." */ - +if userChallenges.isEmpty{ + print("No challenges") +} else if userChallenges.count == 1 { + print("The challenge you have choosen is \(userChallenges[0])") +} else { + print("You have chosen multiple challenges") +} //: [Previous](@previous) | page 2 of 4 | [Next: Exercise - Dictionaries](@next) diff --git a/Lab - Collections.playground/Pages/3. Exercise - Dictionaries.xcplaygroundpage/Contents.swift b/Lab - Collections.playground/Pages/3. Exercise - Dictionaries.xcplaygroundpage/Contents.swift index e3d52d8..9a75627 100644 --- a/Lab - Collections.playground/Pages/3. Exercise - Dictionaries.xcplaygroundpage/Contents.swift +++ b/Lab - Collections.playground/Pages/3. Exercise - Dictionaries.xcplaygroundpage/Contents.swift @@ -3,33 +3,41 @@ Create a variable `[String: Int]` dictionary that can be used to look up the number of days in a particular month. Use a dictionary literal to initialize it with January, February, and March. January contains 31 days, February has 28, and March has 31. Print the dictionary. */ - +var daysMonths: [String: Int] = ["January": 31, "February": 28, "March": 31] +print(daysMonths) /*: Using subscripting syntax to add April to the collection with a value of 30. Print the dictionary. */ - +daysMonths["Aporil"] = 30 +print(daysMonths) /*: It's a leap year! Update the number of days in February to 29 using the `updateValue(_:, forKey:)` method. Print the dictionary. */ - +daysMonths.updateValue(29, forKey: "February") +print(daysMonths) /*: Use if-let syntax to retrieve the number of days under "January". If the value is there, print "January has 31 days", where 31 is the value retrieved from the dictionary. */ - +if let daysJanuary = daysMonths["January"] { + print("January has \(daysJanuary) days") +} /*: Given the following arrays, create a new [String : [String]] dictionary. `shapesArray` should use the key "Shapes" and `colorsArray` should use the key "Colors". Print the resulting dictionary. */ let shapesArray = ["Circle", "Square", "Triangle"] let colorsArray = ["Red", "Green", "Blue"] - - +let shapesColorsArray : [String: [String]] = ["Shapes": shapesArray, "Colors": colorsArray] +print(shapesColorsArray) /*: Print the last element of `colorsArray`, accessing it through the dictionary you've created. You'll have to use if-let syntax or the force unwrap operator to unwrap what is returned from the dictionary before you can access an element of the array. */ - +var dim = shapesArray.count +if let extractColorArray = shapesColorsArray["Colors"]{ + print(extractColorArray[dim-1]) +} //: [Previous](@previous) | page 3 of 4 | [Next: App Exercise - Pacing](@next) diff --git a/Lab - Collections.playground/Pages/4. App Exercises - Pacing.xcplaygroundpage/Contents.swift b/Lab - Collections.playground/Pages/4. App Exercises - Pacing.xcplaygroundpage/Contents.swift index 6b5ba08..b6c309d 100644 --- a/Lab - Collections.playground/Pages/4. App Exercises - Pacing.xcplaygroundpage/Contents.swift +++ b/Lab - Collections.playground/Pages/4. App Exercises - Pacing.xcplaygroundpage/Contents.swift @@ -7,27 +7,33 @@ Create a dictionary `paces` of type [String: Double] and assign it a dictionary literal with "Easy", "Medium", and "Fast" keys corresponding to values of 10.0, 8.0, and 6.0. These numbers correspond to mile pace in minutes. Print the dictionary. */ - +var paces: [String:Double] = ["Easy": 10.0, "Medium":8.0, "Fast":6.0] +print(paces) /*: Add a new key/value pair to the dictionary. The key should be "Sprint" and the value should be 4.0. Print the dictionary. */ - +paces["Sprint"] = 4.0 +print(paces) /*: Imagine the user in question gets faster over time and decides to update his/her pacing on runs. Update the values of "Medium" and "Fast" to 7.5 and 5.8, respectively. Print the dictionary. */ - - +paces["Mediun"] = 7.5 +paces["Fast"] = 5.8 +print(paces) /*: Imagine the user in question decides not to store "Sprint" as one his/her regular paces. Remove "Sprint" from the dictionary. Print the dictionary. */ - +paces.removeValue(forKey: "Sprint") +print(paces) /*: When a user chooses a pace, you want the app to print a statement stating that it will keep him/her on pace. Imagine a user chooses "Medium." Accessing the value from the dictionary, print a statement saying "Okay! I'll keep you at a minute mile pace." */ - +if let pace = paces["Medium"]{ + print("Okay! I'll keep you at a \(pace) minute mile pace.") +} /*: diff --git a/Lab - Constants and Variables.playground/Pages/1. Exercise - Constants.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/1. Exercise - Constants.xcplaygroundpage/Contents.swift index 8721318..110104c 100644 --- a/Lab - Constants and Variables.playground/Pages/1. Exercise - Constants.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/1. Exercise - Constants.xcplaygroundpage/Contents.swift @@ -3,16 +3,17 @@ Declare a constant called `friends` to represent the number of friends you have on social media. Give it a value between 50 and 1000. Print out the value by referencing your constant. */ - +let friends = 500 +print(friends) /*: Now assume you go through and remove friends that aren't active on social media. Attempt to update your `friends` constant to a lower number than it currently is. Observe what happens and then move to the next step. */ - + // friends = 200 It is costant!!! /*: Does the above code compile? Why not? Print your explanation to the console using the `print` function. Go back and delete your line of code that updates the `friends` constant to a lower number so that the playground will compile properly. */ - + print("It is costant!") //: page 1 of 10 | [Next: App Exercise - Step Goal](@next) diff --git a/Lab - Constants and Variables.playground/Pages/10. App Exercise - Percent Completed.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/10. App Exercise - Percent Completed.xcplaygroundpage/Contents.swift index 21166b7..754eddb 100644 --- a/Lab - Constants and Variables.playground/Pages/10. App Exercise - Percent Completed.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/10. App Exercise - Percent Completed.xcplaygroundpage/Contents.swift @@ -5,12 +5,12 @@ You decide that your fitness tracking app should show the user what percentage of his/her goal has been achieved so far today. Declare a variable called `percentCompleted` and set it to 0. Do not explicity assign it a type. */ - +var percentCompleted: Double = 0 /*: Imagine that partway through the day a user has taken 3,467 steps out of the 10,000 step goal. This means he/she is 34.67% of the way to his/her goal. Assign 34.67 to `percentCompleted`. Does the code compile? Go back and explicity assign a type to `percentCompleted` that will allow the code to compile. */ - +percentCompleted = 34.67 /*: diff --git a/Lab - Constants and Variables.playground/Pages/2. App Exercise - Step Goal.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/2. App Exercise - Step Goal.xcplaygroundpage/Contents.swift index b71a821..1ad0504 100644 --- a/Lab - Constants and Variables.playground/Pages/2. App Exercise - Step Goal.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/2. App Exercise - Step Goal.xcplaygroundpage/Contents.swift @@ -5,11 +5,12 @@ Your fitness tracking app needs to know goal number of steps per day. Create a constant `goalSteps` and set it to 10000. */ - +let goalSteps = 10000 /*: Use two `print` functions to print two separate lines to the console. The first line should say "Your step goal for the day is:", and the second line should print the value of `goalSteps` by referencing your constant. */ - +print("Your step goal for the day is:") +print(goalSteps) //: [Previous](@previous) | page 2 of 10 | [Next: Exercise - Variables](@next) diff --git a/Lab - Constants and Variables.playground/Pages/3. Exercise - Variables.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/3. Exercise - Variables.xcplaygroundpage/Contents.swift index 1b6fe9b..0e1dc1f 100644 --- a/Lab - Constants and Variables.playground/Pages/3. Exercise - Variables.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/3. Exercise - Variables.xcplaygroundpage/Contents.swift @@ -3,16 +3,18 @@ Declare a variable `schooling` and set it to the number of years of school that you have completed. Print `schooling` to the console. */ - +var schooling = 18 +print(schooling) /*: Now imagine you just completed an additional year of school, and update the `schooling` variable accordingly. Print `schooling` to the console. */ - +schooling = 19 +print(schooling) /*: Does the above code compile? Why is this different than trying to update a constant? Print your explanation to the console using the `print` function. */ - +print("A variable could change her value") //: [Previous](@previous) | page 3 of 10 | [Next: App Exercise - Step Count](@next) diff --git a/Lab - Constants and Variables.playground/Pages/4. App Exercise - Step Count.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/4. App Exercise - Step Count.xcplaygroundpage/Contents.swift index 4c95fb5..bb133b9 100644 --- a/Lab - Constants and Variables.playground/Pages/4. App Exercise - Step Count.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/4. App Exercise - Step Count.xcplaygroundpage/Contents.swift @@ -5,11 +5,12 @@ Create a variable called `steps` that will keep track of the number of steps you take throughout the day. Set its initial value to 0 to represent the step count first thing in the morning. Print `steps` to the console. */ - +var steps = 0 +print(steps) /*: Now assume the tracker has been keeping track of steps all morning, and you want to show the user the latest step count. Update `steps` to be 2000. Print `steps` to the console. Then print "Good job! You're well on your way to your daily goal." */ - - +steps = 2000 +print("Good job! You're well on your way to your daily goal.") //: [Previous](@previous) | page 4 of 10 | [Next: Exercise - Constant or Variable?](@next) diff --git a/Lab - Constants and Variables.playground/Pages/5. Exercise - Constant Or Variable.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/5. Exercise - Constant Or Variable.xcplaygroundpage/Contents.swift index 1d38a49..6066686 100644 --- a/Lab - Constants and Variables.playground/Pages/5. Exercise - Constant Or Variable.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/5. Exercise - Constant Or Variable.xcplaygroundpage/Contents.swift @@ -10,7 +10,11 @@ For each of the metrics above, declare either a constant or a variable and assign it a value corresponding to a hypothetical post. Be sure to use proper naming conventions. */ - +var numbersLike = 100 +var numbersComment = 20 +let yearCreated = 2019 +let monthCreated = 6 +let dayCreated = 1 diff --git a/Lab - Constants and Variables.playground/Pages/6. App Exercise - Constant or Variable.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/6. App Exercise - Constant or Variable.xcplaygroundpage/Contents.swift index a9bfc4b..ab36ea1 100644 --- a/Lab - Constants and Variables.playground/Pages/6. App Exercise - Constant or Variable.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/6. App Exercise - Constant or Variable.xcplaygroundpage/Contents.swift @@ -11,6 +11,16 @@ - Goal number of steps: The user's goal for number of steps to take each day - Average heart rate: The user's average heart rate over the last 24 hours */ +let name = "Giovanna" +print("It is fixed") +var age = 30 +print("It every year change") +var stepsDay = 10000 +print("Everyday it could change") +let stepsGoal = 20000 +print("It is fixed ...") +var averageHeartRate = 62 +print("Every day it could be different") diff --git a/Lab - Constants and Variables.playground/Pages/7. Exercise - Types and Type Safety.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/7. Exercise - Types and Type Safety.xcplaygroundpage/Contents.swift index 6a26c32..6f08410 100644 --- a/Lab - Constants and Variables.playground/Pages/7. Exercise - Types and Type Safety.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/7. Exercise - Types and Type Safety.xcplaygroundpage/Contents.swift @@ -3,21 +3,26 @@ Declare two variables, one called `firstDecimal` and one called `secondDecimal`. Both should have decimal values. Look at both of their types by holding Option and clicking on the variable name. */ - +var firstDecimal = 2.0 +var secondDecimal = 10.0 /*: Declare a variable called `trueOrFalse` and give it a boolean value. Try to assign it to `firstDecimal` like so: `firstDecimal = trueOrFalse`. Does it compile? Print a statement to the console explaining why not, and remove the line of code that will not compile. */ - +var trueOrFalse = true +// firstDecimal = trueOrFalse +print("the cariables are of different type") /*: Declare a variable and give it a string value. Then try to assign it to `firstDecimal`. Does it compile? Print a statement to the console explaining why not, and remove the line of code that will not compile. */ - - +var name = "Giovanna" +//firstDecimal = name +print("the cariables are of different type") /*: Finally, declare a variable with a whole number value. Then try to assign it to `firstDecimal`. Why won't this compile even though both variables are numbers? Print a statement to the console explaining why not, and remove the line of code that will not compile. */ - - +var wholeNumber = 100 +//firstDecimal = wholeNumber +print("the cariables are of different type") //: [Previous](@previous) | page 7 of 10 | [Next: App Exercise - Tracking Different Types](@next) diff --git a/Lab - Constants and Variables.playground/Pages/8. App Exercise - Tracking Different Types.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/8. App Exercise - Tracking Different Types.xcplaygroundpage/Contents.swift index 1badf6b..ec57fc4 100644 --- a/Lab - Constants and Variables.playground/Pages/8. App Exercise - Tracking Different Types.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/8. App Exercise - Tracking Different Types.xcplaygroundpage/Contents.swift @@ -5,11 +5,12 @@ You have declared a number of constants and variables to keep track of fitness information. Declare one more variable with a boolean value called `hasMetStepGoal`. */ - +var hasMetStepGoal = true /*: When you declared a constant for goal number of steps and a variable for current step count, you likely assigned each a value in the thousands. This can be difficult to read. Redeclare this constant and variable and, when assigning each a value in the thousands, format the number so that it is more readable. */ - +let goalSteps = 30_000 +var numberSteps = 340_000 //: [Previous](@previous) | page 8 of 10 | [Next: Exercise - Type Inference and Required Values](@next) diff --git a/Lab - Constants and Variables.playground/Pages/9. Exercise - Type Inference and Required Values.xcplaygroundpage/Contents.swift b/Lab - Constants and Variables.playground/Pages/9. Exercise - Type Inference and Required Values.xcplaygroundpage/Contents.swift index 5c81e84..626318b 100644 --- a/Lab - Constants and Variables.playground/Pages/9. Exercise - Type Inference and Required Values.xcplaygroundpage/Contents.swift +++ b/Lab - Constants and Variables.playground/Pages/9. Exercise - Type Inference and Required Values.xcplaygroundpage/Contents.swift @@ -3,21 +3,23 @@ Declare a variable called `name` of type `String`, but do not give it a value. Print `name` to the console. Does the code compile? Remove any code that will not compile. */ - +var name : String +//print(String) /*: Now assign a value to `name`, and print it to the console. */ - +name = "Giovanna" +print(name) /*: Declare a variable called `distanceTraveled` and set it to 0. Do not give it an explicit type. */ - +var distanceTraveled: Double = 0 /*: Now assign a value of 54.3 to `distanceTraveled`. Does the code compile? Go back and set an explicit type on `distanceTraveled` so the code will compile. */ - +distanceTraveled = 54.3 //: [Previous](@previous) | page 9 of 10 | [Next: App Exercise - Percent Completed](@next) diff --git a/Lab - Control Flow.playground/Pages/1. Exercise - Logical Operators.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/1. Exercise - Logical Operators.xcplaygroundpage/Contents.swift index e3db378..bc83905 100644 --- a/Lab - Control Flow.playground/Pages/1. Exercise - Logical Operators.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/1. Exercise - Logical Operators.xcplaygroundpage/Contents.swift @@ -10,46 +10,46 @@ 1. `9 == 9` */ - - +print(true) +print(9==9) /*: 2. `9 != 9` */ - - +print(false) +print(9 != 9) /*: 3. `47 > 90` */ - - +print(false) +print( 47 > 90) /*: 4. `47 < 90` */ - - +print(true) +print(47 < 90) /*: 5. `4 <= 4` */ - - +print(true) +print(4 <= 4) /*: 6. `4 >= 5` */ - - +print(false) +print(4 >= 5) /*: 7. `(47 > 90) && (47 < 90)` */ - - +print(false) +print((47 > 90) && (47 < 90)) /*: 8. `(47 > 90) || (47 < 90)` */ - - +print(true) +print((47 > 90) || (47 < 90)) /*: 9. `!true` */ - - + print(false) + print(!true) //: page 1 of 9 | [Next: Exercise - If and If-Else Statements](@next) diff --git a/Lab - Control Flow.playground/Pages/2. Exercise - If and If-Else Statements.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/2. Exercise - If and If-Else Statements.xcplaygroundpage/Contents.swift index 5bb5325..d74e4ee 100644 --- a/Lab - Control Flow.playground/Pages/2. Exercise - If and If-Else Statements.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/2. Exercise - If and If-Else Statements.xcplaygroundpage/Contents.swift @@ -4,18 +4,33 @@ Imagine you're creating a machine that will count your money for you and tell you how wealthy you are based on how much money you have. A variable `dollars` has been given to you with a value of 0. Write an if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0. Observe what is printed to the console. */ var dollars = 0 - - +if dollars == 0 +{ + print("Sorry, kid. You're broke!") +} /*: `dollars` has been updated below to have a value of 10. Write an an if-else statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, but prints "You've got some spending money!" otherwise. Observe what is printed to the console. */ dollars = 10 - +if dollars == 0 { + print("Sorry, kid. You're broke!") +} else { + print("You've got some spending money!") +} /*: `dollars` has been updated below to have a value of 105. Write an an if-else-if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, prints "You've got some spending money!" if `dollars` is less than 100, and prints "Looks to me like you're rich!" otherwise. Observe what is printed to the console. */ dollars = 105 - - +if dollars == 0 { + print("Sorry, kid. You're broke!") +} +else if dollars < 100 +{ + print("You've got some spending money!") +} +else +{ + print("Looks to me like you're rich!") +} //: [Previous](@previous) | page 2 of 9 | [Next: App Exercise - Fitness Decisions](@next) diff --git a/Lab - Control Flow.playground/Pages/3. App Exercise - Fitness Decisions.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/3. App Exercise - Fitness Decisions.xcplaygroundpage/Contents.swift index d0d23b3..1544dd6 100644 --- a/Lab - Control Flow.playground/Pages/3. App Exercise - Fitness Decisions.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/3. App Exercise - Fitness Decisions.xcplaygroundpage/Contents.swift @@ -5,11 +5,22 @@ You want your fitness tracking app to give as much encouragement as possible to your users. Create a variable `steps` equal to the number of steps you guess you've taken today. Create a constant `stepGoal` equal to 10,000. Write an if-else statement that will print "You're almost halfway there!" if `steps` is less than half of `stepGoal`, and will print "You're over halfway there!" if `steps` is greater than half of `stepGoal`. */ - - +var steps = 4928 +let stepGoal = 10000 +if (steps < stepGoal / 2) { + print("You're almost halfway there!") +} else { + print("You're over halfway there!") +} /*: Now create a new, but similar, if-else-if statement that prints "Way to get a good start today!" if `steps` is less than a tenth of `stepGoal`, prints "You're almost halfway there!" if `steps` is less than half of `stepGoal`, and prints "You're over halfway there!" if `steps` is greater than half of `stepGoal`. */ - +if (steps < stepGoal / 10) { + print("Way to get a good start today!") +} else if (steps < stepGoal / 2) { + print("You're almost halfway there!") +} else { + print("You're over halfway there") +} //: [Previous](@previous) | page 3 of 9 | [Next: Exercise - Boolean Practice](@next) diff --git a/Lab - Control Flow.playground/Pages/4. Exercise - Boolean Practice.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/4. Exercise - Boolean Practice.xcplaygroundpage/Contents.swift index 5db9740..0ee789f 100644 --- a/Lab - Control Flow.playground/Pages/4. Exercise - Boolean Practice.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/4. Exercise - Boolean Practice.xcplaygroundpage/Contents.swift @@ -13,6 +13,12 @@ let hasFish = true let hasPizza = false let hasVegan = true +if (hasFish || hasPizza) && hasVegan { + print("Let's go!") +} else { + print("Sorry, we'll have to think of somewhere else.") +} + /*: Imagine you're trying to decide whether or not to go on a walk. You decide that you'll go on a walk if it's not raining or if it's 82 degress or warmer and sunny out. Create a constant `isNiceWeather` that is equal to an expression that evaluates to a boolean indicating whether or not the weather is nice enough for you to go for a walk. Write an if statement that will print "I'm going for a walk!" if the weather is nice. @@ -21,5 +27,8 @@ let temp = 82 let isRaining = true let isSunny = true - +if !isRaining || (temp >= 82 && isSunny) +{ + print("I'm going for a walk!") +} //: [Previous](@previous) | page 4 of 9 | [Next: App Exercise - Target Heart Rate](@next) diff --git a/Lab - Control Flow.playground/Pages/5. App Exercise - Target Heart Rate.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/5. App Exercise - Target Heart Rate.xcplaygroundpage/Contents.swift index 8740e75..8a01c35 100644 --- a/Lab - Control Flow.playground/Pages/5. App Exercise - Target Heart Rate.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/5. App Exercise - Target Heart Rate.xcplaygroundpage/Contents.swift @@ -11,5 +11,11 @@ let targetLowerBound = 120 let targetUpperBound = 150 let currentHR = 147 - +if currentHR < 120 { + print("You're doing great, but try to push it a bit!") +} else if currentHR >= 120 && currentHR <= 150 { + print("You're right on track!") +} else { + print("You're on fire! Slow it down just a bit.") +} //: [Previous](@previous) | page 5 of 9 | [Next: Exercise - Switch Statements](@next) diff --git a/Lab - Control Flow.playground/Pages/6. Switch Statements.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/6. Switch Statements.xcplaygroundpage/Contents.swift index ed3e397..9607b4d 100644 --- a/Lab - Control Flow.playground/Pages/6. Switch Statements.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/6. Switch Statements.xcplaygroundpage/Contents.swift @@ -3,11 +3,19 @@ Imagine you're on a baseball team nearing the end of the season. Create a `leaguePosition` constant with a value of 1. Using a `switch` statement, print "Champions!" if the `leaguePosition` is 1, "Runners up" if the value is 2, "Third place" if the value is 3, and "Bad season!" in all other cases. */ - - +let leaguePosition = 1 +switch leaguePosition { +case 1: print("Champions!") +case 2: print("Runners up") +case 3: print("Third place") +default: print("Bad season!") +} /*: Write a new `switch` statement that prints "Medal winner" if `leaguePosition` is within the range of 1-3. Otherwise, print "No medal awarded". */ - +switch leaguePosition { +case 1...3: print("Medal winner") +default: print("No medal awarded") +} //: [Previous](@previous) | page 6 of 9 | [Next: App Exercise - Heart Rate Zones](@next) diff --git a/Lab - Control Flow.playground/Pages/7. App Exercise - Heart Rate Zones.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/7. App Exercise - Heart Rate Zones.xcplaygroundpage/Contents.swift index 40f36d4..94efbad 100644 --- a/Lab - Control Flow.playground/Pages/7. App Exercise - Heart Rate Zones.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/7. App Exercise - Heart Rate Zones.xcplaygroundpage/Contents.swift @@ -16,6 +16,20 @@ If `currentHR` is above the listed zones, print some kind of warning asking the user to slow down. */ let currentHR = 128 +switch currentHR { +case 100...120: + print("You are in the Very Light zone. Activity in this zone helps with recovery.") +case 121...140: + print("You are in the Light zone. Activity in this zone helps improve basic endurance and fat burning.") +case 141...160: + print("You are in the Moderate zone. Activity in this zone helps improve aerobic fitness.") +case 161...180: + print("You are in the Hard zone. Activity in this zone increases maximum performance capacity for shorter sessions.") +case 181...200: + print("You are in the Maximum zone. Activity in this zone helps fit athletes develop speed.") +default: + print("You might want to slow down. This heart rate may not be safe.") +} //: [Previous](@previous) | page 7 of 9 | [Next: Exercise - Ternary Operator](@next) diff --git a/Lab - Control Flow.playground/Pages/8. Exercise - Ternary Operator.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/8. Exercise - Ternary Operator.xcplaygroundpage/Contents.swift index 24cbb56..ffc3671 100644 --- a/Lab - Control Flow.playground/Pages/8. Exercise - Ternary Operator.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/8. Exercise - Ternary Operator.xcplaygroundpage/Contents.swift @@ -6,11 +6,10 @@ let number1 = 14 let number2 = 25 -var largest: Int +/*var largest: Int if number1 > number2 { largest = number1 } else { largest = number2 -} - -//: [Previous](@previous) | page 8 of 9 | [Next: App Exercise - Ternary Messages](@next) +}*/ +let largest = number1 > number2 ? number1 : number2 diff --git a/Lab - Control Flow.playground/Pages/9. App Exercise - Ternary Messages.xcplaygroundpage/Contents.swift b/Lab - Control Flow.playground/Pages/9. App Exercise - Ternary Messages.xcplaygroundpage/Contents.swift index 5c86dde..74528ea 100644 --- a/Lab - Control Flow.playground/Pages/9. App Exercise - Ternary Messages.xcplaygroundpage/Contents.swift +++ b/Lab - Control Flow.playground/Pages/9. App Exercise - Ternary Messages.xcplaygroundpage/Contents.swift @@ -8,12 +8,12 @@ let stepGoal = 10000 let steps = 3948 -if steps < stepGoal / 2 { +/*if steps < stepGoal / 2 { print("Almost halfway!") } else { print("Over halfway!") -} - +}*/ +print(steps < stepGoal / 2 ? "Almost halfway!" : "Over halfway!") /*: diff --git a/Lab - Enumerations.playground/Pages/1. Exercise - Enumerations.xcplaygroundpage/Contents.swift b/Lab - Enumerations.playground/Pages/1. Exercise - Enumerations.xcplaygroundpage/Contents.swift index dc7d938..54c3429 100644 --- a/Lab - Enumerations.playground/Pages/1. Exercise - Enumerations.xcplaygroundpage/Contents.swift +++ b/Lab - Enumerations.playground/Pages/1. Exercise - Enumerations.xcplaygroundpage/Contents.swift @@ -3,31 +3,77 @@ Define a `Suit` enum with four possible cases: `clubs`, `spades`, `diamonds`, and `hearts`. */ - +enum Suit { + case clubs + case spades + case diamonds + case hearts +} /*: Imagine you are being shown a card trick and have to draw a card and remember the suit. Create a variable instance of `Suit` called `cardInHand` and assign it to the `hearts` case. Print out the instance. */ - +var cardInHand = Suit.hearts +print("Tha card in my hand is \(cardInHand)") /*: Now imagine you have to put back the card you drew and draw a different card. Update the variable to be a spade instead of a heart. */ - +cardInHand = .spades /*: Imagine you are writing an app that will display a fun fortune (i.e. something like "You will soon find what you seek.") based on cards drawn. Write a function called `getFortune(cardSuit:)` that takes a parameter of type `Suit`. Inside the body of the function, write a switch statement based on the value of `cardSuit`. Print a different fortune for each `Suit` value. Call the function a few times, passing in different values for `cardSuit` each time. */ +func getFortune(cardSiut: Suit) { + switch cardSiut { + case .clubs: + print("🤷‍♀️") + case .diamonds: + print("👰") + case .hearts: + print("💔") + case .spades: + print("🧜🏼‍♂️") + } +} +getFortune(cardSiut: .clubs) +getFortune(cardSiut: .diamonds) +getFortune(cardSiut: .hearts) +getFortune(cardSiut: .spades) /*: Create a `Card` struct below. It should have two properties, one for `suit` of type `Suit` and another for `value` of type `Int`. */ - +struct Card { + enum Value { + case ace + case two + case three + case four + case five + case six + case seven + case eight + case nine + case ten + case jack + case queen + case king + } + var suit: Suit + // var value: Int + var value: Value +} /*: How many values can playing cards have? How many values can `Int` be? It would be safer to have an enum for the card's value as well. Inside the struct above, create an enum for `Value`. It should have cases for `ace`, `two`, `three`, `four`, `five`, `six`, `seven`, `eight`, `nine`, `ten`, `jack`, `queen`, `king`. Change the type of `value` from `Int` to `Value`. Initialize two `Card` objects and print a statement for each that details the card's value and suit. */ +let firstCard = Card(suit: .clubs, value: .ace) +let secondCard = Card(suit: .diamonds, value: .two) +print("The first card is \(firstCard.value) of \(firstCard.suit)") +print("The second card is \(secondCard.value) of \(secondCard.suit)") + //: page 1 of 2 | [Next: App Exercise - Swimming Workouts](@next) diff --git a/Lab - Functions.playground/Pages/1. Exercise - Create Functions.xcplaygroundpage/Contents.swift b/Lab - Functions.playground/Pages/1. Exercise - Create Functions.xcplaygroundpage/Contents.swift index 37d509b..91927a6 100644 --- a/Lab - Functions.playground/Pages/1. Exercise - Create Functions.xcplaygroundpage/Contents.swift +++ b/Lab - Functions.playground/Pages/1. Exercise - Create Functions.xcplaygroundpage/Contents.swift @@ -3,11 +3,35 @@ Write a function called `introduceMyself` that prints a brief introduction of yourself. Call the function and observe the printout. */ +func introduceMyself() { + print("Ciao, mi chiamo Giovanna.") +} +introduceMyself() /*: Write a function called `magicEightBall` that generates a random number and then uses either a switch statement or if-else-if statements to print different responses based on the random number generated. `let randomNum = Int.random(in: 0...4)` will generate a random number from 0 to 4, after which you can print different phrases corresponding to the number generated. Call the function multiple times and observe the different printouts. */ +import Foundation +func magicEightBall() { + let randomNum = Int.random(in: 0...4) + switch randomNum { + case 0: + print("E' uscito 0") + case 1: + print("E' uscito 1") + case 2: + print("E' uscito 2") + case 3: + print("E' uscito 3") + default: + print("E' uscito 4") + } +} + +for _ in 0...9 { + magicEightBall() +} //: page 1 of 6 | [Next: App Exercise - A Functioning App](@next) diff --git a/Lab - Functions.playground/Pages/2. App Exercise - A Functioning App.xcplaygroundpage/Contents.swift b/Lab - Functions.playground/Pages/2. App Exercise - A Functioning App.xcplaygroundpage/Contents.swift index 17808ef..ec6d908 100644 --- a/Lab - Functions.playground/Pages/2. App Exercise - A Functioning App.xcplaygroundpage/Contents.swift +++ b/Lab - Functions.playground/Pages/2. App Exercise - A Functioning App.xcplaygroundpage/Contents.swift @@ -8,12 +8,34 @@ A reoccurring process like this is a perfect candidate for a function. Write a function called `incrementSteps` after the declaration of `steps` below that will increment `steps` by one and then print its value. Call the function multiple times and observe the printouts. */ var steps = 0 +func incrementSteps() { + steps += 1 + print(steps) +} +for _ in 0 ... 100 { + incrementSteps() +} /*: Similarly, if you want to regularly provide progress updates to your user, you can put your control flow statements that check on progress into a function. Write a function called `progressUpdate` after the declaration of `goal` below. The function should print "You're off to a good start." if `steps` is less than 10% of `goal`, "You're almost halfway there!" if `steps` is less than half of `goal`, "You're over halfway there!" if `steps` is less than 90% of `goal`, "You're almost there!" if `steps` is less than `goal`, and "You beat your goal!" otherwise. Call the function and observe the printout. Remember, you can convert numbers using the appropriate Int or Double initializer. */ -let goal = 10000 +let goal = 100 +func progressUpdate() { + let percentSteps = Double(steps)/Double(goal) + if percentSteps < 0.1 { + print("You're off to a good start.") + } else if percentSteps < 0.5 { + print("You're almost halfway there!") + } else if percentSteps < 0.9 { + print("You're over halfway there!") + } else if steps < goal { + print("You're almost there!") + } else { + print("You beat your goal!") + } +} +progressUpdate() //: [Previous](@previous) | page 2 of 6 | [Next: Exercise - Parameters and Argument Labels](@next) diff --git a/Lab - Functions.playground/Pages/3. Exercise - Parameters and Argument Labels.xcplaygroundpage/Contents.swift b/Lab - Functions.playground/Pages/3. Exercise - Parameters and Argument Labels.xcplaygroundpage/Contents.swift index 33158a5..2793ffe 100644 --- a/Lab - Functions.playground/Pages/3. Exercise - Parameters and Argument Labels.xcplaygroundpage/Contents.swift +++ b/Lab - Functions.playground/Pages/3. Exercise - Parameters and Argument Labels.xcplaygroundpage/Contents.swift @@ -3,16 +3,28 @@ Write a new introduction function called `introduction`. It should take two `String` parameters, `name` and `home`, and one `Int` parameter, `age`. The function should print a brief introduction. I.e. if "Mary," "California," and 32 were passed into the function, it might print "Mary, 32, is from California." Call the function and observe the printout. */ +func introduction(name: String, home: String, age: Int) { + print("\(name), \(age), is from \(home).") +} +introduction(name: "Mary", home: "California", age: 32) /*: Write a function called `almostAddition` that takes two `Int` arguments. The first argument should not require an argument label. The function should add the two arguments together, subtract 2, then print the result. Call the function and observe the printout. */ +func almostAddition(_ firstNumber: Int, secondNumber: Int) { + print(firstNumber + secondNumber - 2) +} +almostAddition(100, secondNumber: 84) /*: Write a function called `multiply` that takes two `Double` arguments. The function should multiply the two arguments and print the result. The first argument should not require a label, and the second argument should have an external label, "by", that differs from the internal label. Call the function and observe the printout. */ +func multiply(_ firstNumber: Double, by secondNumber: Double) { + print(firstNumber*secondNumber) +} +multiply(9.7, by: 2.9) //: [Previous](@previous) | page 3 of 6 | [Next: App Exercise - Progress Updates](@next) diff --git a/Lab - Functions.playground/Pages/4. App Exercise - Progress Updates.xcplaygroundpage/Contents.swift b/Lab - Functions.playground/Pages/4. App Exercise - Progress Updates.xcplaygroundpage/Contents.swift index 29d57f3..7a392b1 100644 --- a/Lab - Functions.playground/Pages/4. App Exercise - Progress Updates.xcplaygroundpage/Contents.swift +++ b/Lab - Functions.playground/Pages/4. App Exercise - Progress Updates.xcplaygroundpage/Contents.swift @@ -9,11 +9,38 @@ Call the function a number of times, passing in different values of `steps` and `goal`. Observe the printouts and make sure what is printed to the console is what you would expect for the parameters passsed in. */ +func progressUpdate(steps: Int, goal: Int) { + let percent = Double(steps)/Double(goal) + + if percent < 0.1 { + print("You're off to a good start.") + } else if percent < 0.5 { + print("You're almost halfway there!") + } else if percent < 0.9 { + print("You're over halfway there!") + } else if steps < goal { + print("You're almost there!") + } else { + print("You beat your goal!") + } +} - +progressUpdate(steps: 3000, goal: 3000) +progressUpdate(steps: 100, goal: 3000) +progressUpdate(steps: 1300, goal: 3000) +progressUpdate(steps: 2500, goal: 3000) /*: Your fitness tracking app is going to help runners stay on pace to reach their goals. Write a function called pacing that takes four `Double` parameters called `currentDistance`, `totalDistance`, `currentTime`, and `goalTime`. Your function should calculate whether or not the user is on pace to hit or beat `goalTime`. If yes, print "Keep it up!", otherwise print "You've got to push it just a bit harder!" */ +func pacing(currentDistance: Double, totalDistance: Double, currentTime: Double, goalTime: Double) { + let distance = currentTime/(currentDistance/totalDistance) + + if distance < goalTime { + print("Keep it up!") + } else { + print("You've got to push it just a bit harder!") + } +} - +pacing(currentDistance: 10, totalDistance: 1000, currentTime: 3.0, goalTime: 10.0) //: [Previous](@previous) | page 4 of 6 | [Next: Exercise - Return Values](@next) diff --git a/Lab - Functions.playground/Pages/5. Exercise - Return Values.xcplaygroundpage/Contents.swift b/Lab - Functions.playground/Pages/5. Exercise - Return Values.xcplaygroundpage/Contents.swift index 2cdc442..5b92193 100644 --- a/Lab - Functions.playground/Pages/5. Exercise - Return Values.xcplaygroundpage/Contents.swift +++ b/Lab - Functions.playground/Pages/5. Exercise - Return Values.xcplaygroundpage/Contents.swift @@ -3,11 +3,19 @@ Write a function called `greeting` that takes a `String` argument called name, and returns a `String` that greets the name that was passed into the function. I.e. if you pass in "Dan" the return value might be "Hi, Dan! How are you?" Use the function and print the result. */ - +func greeting(name: String) -> String { + return "Hi, \(name)! How are you?" +} +print(greeting(name: "Dan")) /*: Write a function that takes two `Int` arguments, and returns an `Int`. The function should multiply the two arguments, add 2, then return the result. Use the function and print the result. */ +func almostMultiplication(firstNumber: Int, secondNumber: Int) -> Int { + return firstNumber * secondNumber + 2 +} + +print (almostMultiplication(firstNumber: 10, secondNumber: 20)) //: [Previous](@previous) | page 5 of 6 | [Next: App Exercise - Separating Functions](@next) diff --git a/Lab - Functions.playground/Pages/6. App Exercise - Separating Functions.xcplaygroundpage/Contents.swift b/Lab - Functions.playground/Pages/6. App Exercise - Separating Functions.xcplaygroundpage/Contents.swift index 76dc16a..41a8680 100644 --- a/Lab - Functions.playground/Pages/6. App Exercise - Separating Functions.xcplaygroundpage/Contents.swift +++ b/Lab - Functions.playground/Pages/6. App Exercise - Separating Functions.xcplaygroundpage/Contents.swift @@ -7,13 +7,27 @@ As an example, write a function that only does a portion of what your previous `pacing` function did. This function will be called `calculatePace`. It should take three `Double` arguments called `currentDistance`, `totalDistance`, and `currentTime`, and should return a `Double` that will represent the time at which the user will finish the run based on the user's current distance and time. call the function and print the return value. */ +func calculatePace(currentDistance: Double, totalDistance: Double, currentTime: Double) -> Double { + return currentTime/(currentDistance/totalDistance) +} + +print(calculatePace(currentDistance: 100, totalDistance: 1000, currentTime: 2.1)) /*: Now write a function called `pacing` that takes four `Double` arguments called `currentDistance`, `totalDistance`, `currentTime`, and `goalTime`. The function should also return a `String`, which will be the message to show the user. The function should call `calculatePace`, passing in the appropriate values, and capture the return value. The function should then compare the returned value to `goalTime` and if the user is on pace return "Keep it up!", and return "You've got to push it just a bit harder!" otherwise. Call the function and print the return value. */ +func pacing(currentDistance: Double, totalDistance: Double, currentTime: Double, goalTime: Double) -> String { + let distance = calculatePace(currentDistance: currentDistance, totalDistance: totalDistance, currentTime: currentTime) + if distance <= goalTime { + return "Keep it up!" + } else { + return "You've got to push it just a bit harder!" + } +} +print(pacing(currentDistance: 50, totalDistance: 100, currentTime: 4.8, goalTime: 10)) /*: _Copyright © 2018 Apple Inc._ diff --git a/Lab - Guard.playground/Pages/1. Exercise - Guard Statements.xcplaygroundpage/Contents.swift b/Lab - Guard.playground/Pages/1. Exercise - Guard Statements.xcplaygroundpage/Contents.swift index f851c0a..acbab2e 100644 --- a/Lab - Guard.playground/Pages/1. Exercise - Guard Statements.xcplaygroundpage/Contents.swift +++ b/Lab - Guard.playground/Pages/1. Exercise - Guard Statements.xcplaygroundpage/Contents.swift @@ -4,13 +4,22 @@ import UIKit Imagine you want to write a function to calculate the area of a rectangle. However, if you pass a negative number into the function, you don't want it to calculate a negative area. Create a function called `calculateArea` that takes two `Double` parameters, `x` and `y`, and returns an optional `Double`. Write a guard statement at the beginning of the function that verifies each of the parameters is greater than zero and returns `nil` if not. When the guard has succeeded, calculate the area by multiplying `x` and `y` together, then return the area. Call the function once with positive numbers and once with at least one negative number. */ +func calculateArea (x: Double, y: Double)-> Double? { + guard x > 0 && y > 0 else { return nil } + return x*y +} - +calculateArea(x: 34, y: 12.5) +calculateArea(x: -12, y: 100) /*: Create a function called `add` that takes two optional integers as parameters and returns an optional integer. You should use one `guard` statement to unwrap both optional parameters, returning `nil` in the `guard` body if one or both of the parameters doesn't have a value. If both parameters can successfully be unwrapped, return their sum. Call the function once with non-`nil` numbers and once with at least one parameter being `nil`. */ - - +func add(i: Int?, j: Int?)-> Int? { + guard let ii = i, let jj = j else { return nil } + return ii + jj +} +add(i: 4, j: 5) +add(i: nil, j: 5) /*: When working with UIKit objects, you will occasionally need to unwrap optionals to handle user input. For example, the text fields initialized below have `text` properties that are of type `String?`. @@ -30,10 +39,17 @@ firstNameTextField.text = "Jonathan" lastNameTextField.text = "Sanders" ageTextField.text = "28" - +func createUser ()-> User? { + guard let firstName = firstNameTextField.text, let lastName = lastNameTextField.text, let age = ageTextField.text else { return nil } + return User(firstName: firstName, lastName: lastName, age: age) + +} /*: Call the function you made above and capture the return value. Unwrap the `User` with standard optional binding and print a statement using each of its properties. */ - +let User1 = createUser() +if let user = User1 { + print("L'utente si chiama \(user.firstName) \(user.lastName) e ha \(user.age) anni") +} //: page 1 of 2 | [Next: App Exercise - Guard](@next) diff --git a/Lab - Guard.playground/Pages/2. App Exercise - Guard.xcplaygroundpage/Contents.swift b/Lab - Guard.playground/Pages/2. App Exercise - Guard.xcplaygroundpage/Contents.swift index 4fea0bf..92b945f 100644 --- a/Lab - Guard.playground/Pages/2. App Exercise - Guard.xcplaygroundpage/Contents.swift +++ b/Lab - Guard.playground/Pages/2. App Exercise - Guard.xcplaygroundpage/Contents.swift @@ -10,7 +10,17 @@ import UIKit Write a failable initializer that takes parameters for your start and end times, and then checks to see if they are greater than 10 seconds apart using a guard statement. If they are, your initializer should fail. Otherwise, the initializer should set the properties accordingly. */ - +struct Workout { + var startTime: Double + var endTime: Double + + init?(startTime: Double, endTime: Double){ + guard endTime - startTime > 10 else { return nil } + self.startTime = startTime + self.endTime = endTime + } + +} /*: Imagine a screen where a user inputs a meal that they've eaten. If the user taps a "save" button without adding any food, you might want to prompt the user that they haven't actually added anything. @@ -28,12 +38,21 @@ let caloriesTextField = UITextField() foodTextField.text = "Banana" caloriesTextField.text = "23" +func logFood()-> Food?{ + guard let food = foodTextField.text, let calories = caloriesTextField.text, let caloriesNumber = Int(calories) else { return nil + } + return Food(name: food, calories: caloriesNumber) +} + + /*: Call the function you made above and capture the return value. Unwrap the `Food` object with standard optional binding and print a statement about the food using each of its properties. Go back and change the text in `caloriesTextField` to a string that cannot be converted into a number. What happens in that case? */ - +if let food = logFood() { + print("La \(food.name) ha \(food.calories) calorie") +} /*: _Copyright © 2018 Apple Inc._