From 2695533f30c80a21b2bd809d52e32526cc21fd29 Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:47:19 +0200 Subject: [PATCH 01/15] Done introduction --- .../Contents.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Lab - Introduction.playground/Pages/1. Exercise - Use Playgrounds.xcplaygroundpage/Contents.swift b/Lab - Introduction.playground/Pages/1. Exercise - Use Playgrounds.xcplaygroundpage/Contents.swift index cd86d9d..a98d99d 100644 --- a/Lab - Introduction.playground/Pages/1. Exercise - Use Playgrounds.xcplaygroundpage/Contents.swift +++ b/Lab - Introduction.playground/Pages/1. Exercise - Use Playgrounds.xcplaygroundpage/Contents.swift @@ -10,12 +10,14 @@ print("How to use playgrounds to make writing Swift fun and simple") /*: Now print your own phrases to the console. Pick one of your favorite songs. Use your knowledge of the `print` function to display the song title and artist. */ - +print("Harry Chapin - Cats in the craddle") /*: Use multiple `print` functions to write out some of the lyrics to the song. */ - +print("And the cat's in the cradle and the silver spoon") +print("Little boy blue and the man in the moon") +print("\"When you coming home, dad?\" \"I don't know when\"") /*: From 66eeab83f009b482693f26e34aa4f7ce83888199 Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:42:09 +0200 Subject: [PATCH 02/15] Done constants & variables --- .../Contents.swift | 6 +++--- .../Contents.swift | 4 ++-- .../Contents.swift | 6 +++--- .../Contents.swift | 8 +++++--- .../Contents.swift | 9 +++++---- .../Contents.swift | 5 +++++ .../Contents.swift | 15 ++++++++++----- .../Contents.swift | 16 +++++++++++----- .../Contents.swift | 7 +++---- .../Contents.swift | 10 ++++++---- 10 files changed, 53 insertions(+), 33 deletions(-) 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..c881f54 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,16 @@ 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 = 13 /*: 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 = 6 /*: 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("Can't modify a constant, must be a (var)iable") //: 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..54ef0ba 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,11 @@ 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..0ac2780 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 = 10 +print(schooling) /*: Now imagine you just completed an additional year of school, and update the `schooling` variable accordingly. Print `schooling` to the console. */ - +schooling += 1 +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("Code compile and works as expected. Variables are mutable while constants are not") //: [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..042a3f8 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(steps) +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..2f86196 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,6 +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 numberOfLikes = 3 +var numberOfComments = 10 +let creationYear = 2020 +let creationMonth = 6 +let creationDay = 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..5768460 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,11 +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 = "Thomas" +print("Name won't change") +var age = 51 +print("Changes once a year") +var nStepsToday = 500 +print("Changes every day") +let stepsGoal = 800 +print("This piece of code won't change the value, no need to have it mutable") +var avgHeartRate = 39 +print("Changes every 24 hours") /*: Now go back and add a line after each constant or variable declaration. On those lines, print a statement explaining why you chose to declare the piece of information as a constant or variable. */ 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..2615ba4 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,27 @@ 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.2 +var secondDecimal = 3.1 /*: 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("Dosn't compile, can't assign a boolean to a double") /*: 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 myString = "this is a string" +//firstDecimal = myString +print("Dosn't compile, can't assign a string to a double") /*: 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 myInt = 57 +//firstDecimal = myInt +print("Dosn't compile, can't assign an int to a double") //: [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..e2040a3 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,10 @@ 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 = false /*: 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. */ - - +var nStepsToday = 1_500 +let stepsGoal = 2_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..202986b 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(name) /*: Now assign a value to `name`, and print it to the console. */ - +name = "William" +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) From 4e5a62683a6d3be2bfd1d455a3eb83a9dc138203 Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:43:21 +0200 Subject: [PATCH 03/15] Done operators --- .../Contents.swift | 36 ++++++++++++++----- .../Contents.swift | 22 ++++++++---- .../Contents.swift | 25 +++++++++---- .../Contents.swift | 9 ++--- .../Contents.swift | 12 +++---- .../Contents.swift | 12 ++++--- .../Contents.swift | 12 ++++--- .../Contents.swift | 5 ++- 8 files changed, 91 insertions(+), 42 deletions(-) diff --git a/Lab - Operators.playground/Pages/1. Exercise - Basic Arithmetic.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/1. Exercise - Basic Arithmetic.xcplaygroundpage/Contents.swift index 8c68750..d596b60 100644 --- a/Lab - Operators.playground/Pages/1. Exercise - Basic Arithmetic.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/1. Exercise - Basic Arithmetic.xcplaygroundpage/Contents.swift @@ -3,28 +3,38 @@ You decide to build a shed and want to know beforehand the area of your yard that it will take up. Create two constants, `width` and `height`, with values of 10 and 20, respectively. Create an `area` constant that is the result of multiplying the two previous constants together, and print out the result. */ - +let width = 10 +let height = 20 +let area = width*height +print(area) /*: You decide that you'll divide your shed into two rooms. You want to know if dividing it equally will leave enough room for some of your larger storage items. Create a `roomArea` constant that is the result of dividing `area` in half. Print out the result. */ - +let roomArea = Double(area)/2.0 +print(roomArea) /*: Create a `perimeter` constant whose value equals `width` plus `width` plus `height` plus `height`, then print out the result. */ - +let perimeter = width + width + height + height +print(perimeter) /*: Print what you would expect the result of integer division of 10 divided by 3 to be. Create a constant, `integerDivisionResult` that is the result of 10 divided by 3, and print the value. */ - +print("10/3 as int = 3") +let integerDivisionResult = 10/3 +print(integerDivisionResult) /*: Now create two constants, `double10` and `double3`, set to 10 and 3, and declare their types as `Double` values. Declare a final constant `divisionResult` equal to the result of `double10` divided by `double3`. Print the value of `divisionResult`. How does this differ from the value when using integer division? */ - - +let double10: Double = 10 +let double3: Double = 3 +let divisionResult = double10/double3 +print(divisionResult) +print("Double division has the decimal value while integer division only keeps the whole part") /*: Given the value pi (3.1415927), create a `radius` constant with a value of 5.0, then calculate the diameter and circumference of the circle using the following equations, and print the results: @@ -33,16 +43,24 @@ *circumference = 2 * pi * radius.* */ let pi = 3.1415927 +let radius = 5.0 +let diameter = radius * 2 +let circumference = 2 * pi * radius +print(diameter) +print(circumference) /*: Create an integer constant. Using the remainder operator, set its value to the remainder of 12 divided by 5. */ - - +let remainder = 12 % 5 /*: Create two integer constants, `even` and `odd` and set them to any even integer and any odd integer, respectively. For each, print the remainder of dividing the value by 2. Looking at the results, how do you think you could use the remainder operator to determine if an integer is even or odd? */ +let even = 8 +let odd = 5 +print(even % 2) +print(odd % 2) - +print("If x % 2 == 0 x is even") //: page 1 of 8 | [Next: App Exercise - Fitness Calculations](@next) diff --git a/Lab - Operators.playground/Pages/2. App Exercise - Fitness Calculations.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/2. App Exercise - Fitness Calculations.xcplaygroundpage/Contents.swift index 7384367..d979d70 100644 --- a/Lab - Operators.playground/Pages/2. App Exercise - Fitness Calculations.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/2. App Exercise - Fitness Calculations.xcplaygroundpage/Contents.swift @@ -5,16 +5,26 @@ Your fitness tracker keeps track of users' heart rate, but you might also want to display their average heart rate over the last hour. Create three constants, `heartRate1`, `heartRate2`, and `heartRate3`. Give each constant a different value between 60 and 100. Create a constant `addedHR` equal to the sum of all three heart rates. Now create a constant called `averageHR` that equals `addedHR` divided by 3 to get the average. Print the result. */ - - +let heartRate1 = 60 +let heartRate2 = 70 +let heartRate3 = 80 +let addedHR = heartRate1 + heartRate2 + heartRate3 +let averageHR = addedHR / 3 +print(averageHR) /*: Now create three more constants, `heartRate1D`, `heartRate2D`, and `heartRate3D`, equal to the same values as `heartRate1`, `heartRate2`, and `heartRate3`. These new constants should be of type `Double`. Create a constant `addedHRD` equal to the sum of all three heart rates. Create a constant called `averageHRD` that equals the `addedHRD` divided by 3 to get the average of your new heart rate constants. Print the result. Does this differ from your previous average? Why or why not? */ - - +let heartRate1D: Double = 60 +let heartRate2D: Double = 70 +let heartRate3D: Double = 80 +let addedHRD: Double = heartRate1D + heartRate2D + heartRate3D +let averageHRD: Double = addedHRD / 3.0 +print(averageHRD) +print("Doesn't differ from previous average because the sum of the 3 heart rate are a multiple of 3") /*: Imagine that partway through the day a user has taken 3,467 steps out of the 10,000 step goal. Create constants `steps` and `goal`. Both will need to be of type `Double` so that you can perform accurate calculations. `steps` should be assigned the value 3,467, and `goal` should be assigned 10,000. Create a constant `percentOfGoal` that equals an expression that evaluates to the percent of the goal that has been achieved so far. */ - - +let steps: Double = 3_467 +let goal: Double = 10_000 +let percentOfGoal = steps/goal * 100.0 //: [Previous](@previous) | page 2 of 8 | [Next: Exercise - Compound Assignment](@next) diff --git a/Lab - Operators.playground/Pages/3. Exercise - Compound Assignment.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/3. Exercise - Compound Assignment.xcplaygroundpage/Contents.swift index b0c97b5..501f616 100644 --- a/Lab - Operators.playground/Pages/3. Exercise - Compound Assignment.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/3. Exercise - Compound Assignment.xcplaygroundpage/Contents.swift @@ -3,8 +3,12 @@ Declare a variable whose value begins at 10. Using addition, update the value to 15 using the compound assignment operator. Using multiplication, update the value to 30 using compound assignment. Print out the variable's value after each assignment. */ - - +var myVar = 10 +print(myVar) +myVar += 5 +print(myVar) +myVar *= 2 +print(myVar) /*: Create a variable called `piggyBank` that begins at 0. You will use this to keep track of money you earn and spend. For each point below, use the right compound assignment operator to update the balance in your piggy bank. @@ -16,9 +20,16 @@ Print the balance of your piggy bank after each step. */ - - - - - +var piggyBank = 0 +print(piggyBank) +piggyBank += 10 +print(piggyBank) +piggyBank += 20 +print(piggyBank) +piggyBank -= piggyBank/2 +print(piggyBank) +piggyBank *= 3 +print(piggyBank) +piggyBank -= 3 +print(piggyBank) //: [Previous](@previous) | page 3 of 8 | [Next: App Exercise - Counting](@next) diff --git a/Lab - Operators.playground/Pages/4. App Exercise - Counting.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/4. App Exercise - Counting.xcplaygroundpage/Contents.swift index 881654a..22202ab 100644 --- a/Lab - Operators.playground/Pages/4. App Exercise - Counting.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/4. App Exercise - Counting.xcplaygroundpage/Contents.swift @@ -5,13 +5,14 @@ The most basic feature of your fitness tracking app is counting steps. Create a variable `steps` and set it equal to 0. Then increment its value by 1 to simulate a user taking a step. */ - - +var steps = 0 +steps += 1 /*: In addition to tracking steps, your fitness tracking app tracks distance traveled. Create a variable `distance` of type `Double` and set it equal to 50. This will represent the user having traveled 50 feet. You decide, however, to display the distance in meters. 1 meter is approximately equal to 3 feet. Use a compound assignment operator to convert `distance` to meters. Print the result. */ - - +var distance: Double = 50 +distance /= 3 +print(distance) //: [Previous](@previous) | page 4 of 8 | [Next: Exercise - Order of Operations](@next) diff --git a/Lab - Operators.playground/Pages/5. Exercise - Order of Operations.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/5. Exercise - Order of Operations.xcplaygroundpage/Contents.swift index e8378a0..be9326b 100644 --- a/Lab - Operators.playground/Pages/5. Exercise - Order of Operations.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/5. Exercise - Order of Operations.xcplaygroundpage/Contents.swift @@ -3,21 +3,21 @@ Print out what you think 10 + 2 * 5 evaluates to. Then print out the actual expression (i.e. `print(10 + 2 * 5)`) */ - - +print(20) +print(10 + 2 * 5) /*: In a separate `print` statement, add in the necessary parentheses so that addition takes place before multiplication. */ - +print((10 + 2) * 5) /*: Print out what you think 4 * 9 - 6 / 2 evaluates to. Then print out the actual expression. */ - - +print(33) +print(4 * 9 - 6 / 2) /*: In a separate `print` statement, add in the necessary parentheses so that the subtraction is prioritized over the multiplication and division. */ - +print(4 * (9 - 6) / 2) //: [Previous](@previous) | page 5 of 8 | [Next: App Exercise - Complex Fitness Calculations](@next) diff --git a/Lab - Operators.playground/Pages/6. App Exercise - Complex Fitness Calculations.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/6. App Exercise - Complex Fitness Calculations.xcplaygroundpage/Contents.swift index 1f2189c..c78bd66 100644 --- a/Lab - Operators.playground/Pages/6. App Exercise - Complex Fitness Calculations.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/6. App Exercise - Complex Fitness Calculations.xcplaygroundpage/Contents.swift @@ -5,13 +5,17 @@ If you completed the Fitness Calculations exercise, you calculated an average heart rate to display to the user. However, using proper order of operations you can do this in fewer steps. Create three separate heart rate constants, all of type `Double`, with values between 60 and 100. Then create a constant equal to the average heart rate. If you use correct order of operations you can do the heart calculation in one line. */ - - +let heartRate1: Double = 60 +let heartRate2: Double = 70 +let heartRate3: Double = 80 +let avgHeartRate = (heartRate1+heartRate2+heartRate3)/3.0 +print(avgHeartRate) /*: One feature you might want to give users is to display their current body temperature. Create a constant `tempInFahrenheit` equal to 98.6. You may want to also show the temperature in celsius. You can convert fahrenheit to celsius by taking `tempInFahrenheit` and subtracting 32, then multiplying the result by (5.0/9.0). Create a constant `tempInCelsius` that calculates in one line the temperature in celsius. */ - - +let tempInFahrenheit = 98.6 +let tempInCelsius = (tempInFahrenheit - 32) * (5.0/9.0) +print(tempInCelsius) //: [Previous](@previous) | page 6 of 8 | [Next: Exercise - Numeric Type Conversion](@next) diff --git a/Lab - Operators.playground/Pages/7. Exercise - Numeric Type Conversion.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/7. Exercise - Numeric Type Conversion.xcplaygroundpage/Contents.swift index 93698b8..b6d87a4 100644 --- a/Lab - Operators.playground/Pages/7. Exercise - Numeric Type Conversion.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/7. Exercise - Numeric Type Conversion.xcplaygroundpage/Contents.swift @@ -3,16 +3,18 @@ Create an integer constant `x` with a value of 10, and a double constant `y` with a value of 3.2. Create a constant `multipliedAsIntegers` equal to `x` times `y`. Does this compile? If not, fix it by converting your `Double` to an `Int` in the mathematical expression. Print the result. */ - - +let x: Int = 10 +let y: Double = 3.2 +let multipliedAsIntegers = x * Int(y) +print(multipliedAsIntegers) /*: Create a constant `multipliedAsDoubles` equal to `x` times `y`, but this time convert the `Int` to a `Double` in the expression. Print the result. */ - - +let multipliedAsDoubles = Double(x) * y +print(multipliedAsDoubles) /*: Are the values of `multipliedAsIntegers` and `multipliedAsDoubles` different? Print a statement to the console explaining why. */ - +print("Values are different because the first is 10*3 while the second is 10*3.2, with 3 != 3.2") //: [Previous](@previous) | page 7 of 8 | [Next: App Exercise - Converting Types](@next) diff --git a/Lab - Operators.playground/Pages/8. App Exercise - Fitness Conversions.xcplaygroundpage/Contents.swift b/Lab - Operators.playground/Pages/8. App Exercise - Fitness Conversions.xcplaygroundpage/Contents.swift index 5de2f53..1d1a8ab 100644 --- a/Lab - Operators.playground/Pages/8. App Exercise - Fitness Conversions.xcplaygroundpage/Contents.swift +++ b/Lab - Operators.playground/Pages/8. App Exercise - Fitness Conversions.xcplaygroundpage/Contents.swift @@ -7,7 +7,10 @@ Now create a constant `percentOfGoal` of type `Double` that equals the percent of the goal that has been reached so far. You'll need to convert your constants of type `Int` to be of type `Double` in your calculation. */ - +var steps: Int = 500 +let goal: Int = 10_000 +let percentOfGoal: Double = Double(steps)/Double(goal) * 100.0 +print(percentOfGoal) /*: From 51e86b88e130a92d5a48743370a55142ab4000d8 Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:43:43 +0200 Subject: [PATCH 04/15] Done control flow --- .../Contents.swift | 35 ++++++++++--------- .../Contents.swift | 17 +++++++-- .../Contents.swift | 17 +++++++-- .../Contents.swift | 12 +++++-- .../Contents.swift | 10 ++++++ .../Contents.swift | 19 ++++++++-- .../Contents.swift | 17 ++++++++- .../Contents.swift | 8 +---- .../Contents.swift | 11 +++--- 9 files changed, 105 insertions(+), 41 deletions(-) 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..e484217 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,47 @@ 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..c38cdea 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,31 @@ 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..8c2c9e2 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 = 500 +let stepGoal = 10_000 +if steps < stepGoal/2 { + print("You're almost halfway there!") +}else if steps > stepGoal/2 { + 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 if steps > stepGoal/2 { + 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..30c5b6b 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,13 +13,21 @@ 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. */ let temp = 82 -let isRaining = true +let isRaining = false let isSunny = true +let isNiceWeather = !isRaining && temp >= 82 && isSunny +if isNiceWeather { + 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..ed14414 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,15 @@ let targetLowerBound = 120 let targetUpperBound = 150 let currentHR = 147 +let isInTarget = currentHR >= targetLowerBound && currentHR <= targetUpperBound +let isBelowTarget = currentHR < targetLowerBound +let isAboveTarget = currentHR > targetUpperBound +if isInTarget { + print("You're right on track!") +}else if isBelowTarget { + print("You're doing great, but try to push it a bit!") +}else if isAboveTarget { + 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..d12da4c 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,26 @@ 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..773f1e3 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,21 @@ 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 basice 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.") +case 200-999: //480 is the highest HR ever recorded + print("Danger, slow down!") +default: + print("Below significant ranges") +} //: [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..89d2373 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,5 @@ let number1 = 14 let number2 = 25 -var largest: Int -if number1 > number2 { - largest = number1 -} else { - largest = number2 -} - +var largest = number1 > number2 ? number1 : number2 //: [Previous](@previous) | page 8 of 9 | [Next: App Exercise - Ternary Messages](@next) 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..7b91464 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,13 +8,10 @@ let stepGoal = 10000 let steps = 3948 -if steps < stepGoal / 2 { - print("Almost halfway!") -} else { - print("Over halfway!") -} - - +print( steps < stepGoal / 2 + ? "Almost halfway!" + : "Over halfway!" +) /*: _Copyright © 2018 Apple Inc._ From d20dcc56c5a7e718b4c20914b1d24356131e082e Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:43:57 +0200 Subject: [PATCH 05/15] Done strings --- .../Contents.swift | 15 ++++++----- .../Contents.swift | 14 +++++++---- .../Contents.swift | 10 +++++--- .../Contents.swift | 25 ++++++++++++++----- .../Contents.swift | 14 ++++++++--- 5 files changed, 54 insertions(+), 24 deletions(-) diff --git a/Lab - Strings.playground/Pages/1. Exercise - String Basics.xcplaygroundpage/Contents.swift b/Lab - Strings.playground/Pages/1. Exercise - String Basics.xcplaygroundpage/Contents.swift index d17ab77..62bc384 100644 --- a/Lab - Strings.playground/Pages/1. Exercise - String Basics.xcplaygroundpage/Contents.swift +++ b/Lab - Strings.playground/Pages/1. Exercise - String Basics.xcplaygroundpage/Contents.swift @@ -3,7 +3,7 @@ Create a `name` constant and assign it a string literal representing your name. */ - +let name = "Samuel" /*: Create a `favoriteQuote` constant and assign it the following string literal: @@ -15,12 +15,15 @@ - callout(Example): If your favorite quote is "The grass is always greener on the other side" the value of `favoriteQuote` should be such that printing `favoriteQuote` results in the following: * `My favorite quote is "The grass is always greener on the other side."` */ - - +let favoriteQuote = "My favorite quote is \"A bird in the hand is worth two in the bush\"" +print(favoriteQuote) /*: Write an if-else statement that prints "There's nothing here" if `emptyString` is empty, and "It's not as empty as I thought" otherwise. */ -let emptyString = "" - - +let emptyString = "a" +if emptyString.isEmpty { + print("There's nothing here") +}else{ + print("It's not as empty as I thought") +} //: page 1 of 5 | [Next: Exercise - Concatenation and Interpolation](@next) diff --git a/Lab - Strings.playground/Pages/2. Exercise - Concatenation and Interpolation.xcplaygroundpage/Contents.swift b/Lab - Strings.playground/Pages/2. Exercise - Concatenation and Interpolation.xcplaygroundpage/Contents.swift index 2bbe7f2..69501e2 100644 --- a/Lab - Strings.playground/Pages/2. Exercise - Concatenation and Interpolation.xcplaygroundpage/Contents.swift +++ b/Lab - Strings.playground/Pages/2. Exercise - Concatenation and Interpolation.xcplaygroundpage/Contents.swift @@ -3,14 +3,16 @@ Create a `city` constant and assign it a string literal representing your home city. Then create a `state` constant and assign it a string literal representing your home state. Finally, create a `home` constant and use string concatenation to assign it a string representing your home city and state (i.e. Portland, Oregon). Print the value of `home`. */ - - +let city = "Provo" +let state = "Utah" +let home = city + ", " + state +print(home) /*: Use the compound assignment operator (`+=`) to add `home` to `introduction` below. Print the value of `introduction`. */ var introduction = "I live in" - - +introduction += (" " + home) +print(introduction) /*: Declare a `name` constant and assign it your name as a string literal. Then declare an `age` constant and give it your current age as an `Int`. Then print the following phrase using string interpolation: @@ -18,6 +20,8 @@ var introduction = "I live in" Insert `name` where indicated, and insert a mathematical expression that evaluates to your current age plus one where indicated. */ - +let name = "Samuel" +let age = 25 +print("My name is \(name) and after my next birthday I will be \(age+1) years old.") //: [Previous](@previous) | page 2 of 5 | [Next: App Exercise - Notifications](@next) diff --git a/Lab - Strings.playground/Pages/3. App Exercise - Notifications.xcplaygroundpage/Contents.swift b/Lab - Strings.playground/Pages/3. App Exercise - Notifications.xcplaygroundpage/Contents.swift index abb8e54..7bb157d 100644 --- a/Lab - Strings.playground/Pages/3. App Exercise - Notifications.xcplaygroundpage/Contents.swift +++ b/Lab - Strings.playground/Pages/3. App Exercise - Notifications.xcplaygroundpage/Contents.swift @@ -7,8 +7,10 @@ Create `firstName` and `lastName` constants and assign them string literals representing a user's first name and last name, respectively. Create a `fullName` constant that uses string concatenation to combine `firstName` and `lastName`. Print the value of `fullName`. */ - - +let firstName = "Johnny" +let lastName = "Appleseed" +let fullName = firstName + " " + lastName +print(fullName) /*: Occasionally users of your fitness tracking app will beat previous goals or records. You may want to notify them when this happens for encouragement purposes. Create a new constant `congratulations` and assign it a string literal that uses string interpolation to create the following string: @@ -18,6 +20,6 @@ */ let previousBest = 14392 let newBest = 15125 - - +let congratulations = "Congratulations, \(fullName)! You beat your previous daily high score of \(previousBest) steps by walking \(newBest) steps yesterday!" +print(congratulations) //: [Previous](@previous) | page 3 of 5 | [Next: Exercise - String Equality and Comparison](@next) diff --git a/Lab - Strings.playground/Pages/4. Exercise - String Equality and Comparison.xcplaygroundpage/Contents.swift b/Lab - Strings.playground/Pages/4. Exercise - String Equality and Comparison.xcplaygroundpage/Contents.swift index 3ee86db..f5494ab 100644 --- a/Lab - Strings.playground/Pages/4. Exercise - String Equality and Comparison.xcplaygroundpage/Contents.swift +++ b/Lab - Strings.playground/Pages/4. Exercise - String Equality and Comparison.xcplaygroundpage/Contents.swift @@ -3,8 +3,13 @@ Create two constants, `nameInCaps` and `name`. Assign `nameInCaps` your name as a string literal with proper capitalization. Assign `name` your name as a string literal in all lowercase. Write an if-else statement that checks to see if `nameInCaps` and `name` are the same. If they are, print "The two strings are equal", otherwise print "The two strings are not equal." */ - - +let nameInCaps = "SAMUEL" +let name = "samuel" +if name == nameInCaps { + print("The two strings are equal") +}else{ + print("The two strings are not equal.") +} /*: Write a new if-else statement that also checks to see if `nameInCaps` and `name` are the same. However, this time use the `lowercased()` method on each constant to compare the lowercase version of the strings. If they are equal, print the following statement using string interpolations: @@ -14,13 +19,19 @@ - " and are not the same." */ - +if name.lowercased() == nameInCaps.lowercased() { + print("\(name.lowercased()) and \(nameInCaps.lowercased()) are the same") +}else{ + print("\(name.lowercased()) and \(nameInCaps.lowercased()) are not the same") +} /*: Imagine you are looking through a list of names to find any that end in "Jr." Write an if statement below that will check if `junior` has the suffix "Jr.". If it does, print "We found a second generation name!" */ let junior = "Cal Ripken Jr." - +if junior.hasSuffix("Jr.") { + print("We found a second generation name!") +} /*: Suppose you are trying to find a document on your computer that contains Hamlet's famous soliloquy written by Shakespeare. You write a simple app that will check every document to see if it contains the phrase "to be, or not to be". You decide to do part of this with the `contains(_:)` method. Write an if statement below that will check if `textToSearchThrough` contains `textToSearchFor`. If it does, print "I found it!" Be sure to make this functionality case insensitive. @@ -29,10 +40,12 @@ import Foundation let textToSearchThrough = "To be, or not to be--that is the question" let textToSearchFor = "to be, or not to be" - +if textToSearchThrough.lowercased().contains(textToSearchFor) { + print("I found it!") +} /*: Print to the console the number of characters in your name by using the `count` property on `name`. */ - +print(name.count) //: [Previous](@previous) | page 4 of 5 | [Next: App Exercise - Password Entry and User Search](@next) diff --git a/Lab - Strings.playground/Pages/5. App Exercise - Password Entry and User Search.xcplaygroundpage/Contents.swift b/Lab - Strings.playground/Pages/5. App Exercise - Password Entry and User Search.xcplaygroundpage/Contents.swift index e396836..7011212 100644 --- a/Lab - Strings.playground/Pages/5. App Exercise - Password Entry and User Search.xcplaygroundpage/Contents.swift +++ b/Lab - Strings.playground/Pages/5. App Exercise - Password Entry and User Search.xcplaygroundpage/Contents.swift @@ -8,9 +8,14 @@ let storedUserName = "TheFittest11" let storedPassword = "a8H1LuK91" let enteredUserName = "thefittest11" -let enteredPassword: String = "a8H1Luk9" - - +let enteredPassword: String = "a8H1LuK91" + +if enteredUserName.lowercased() == storedUserName.lowercased() + && enteredPassword == storedPassword { + print("You are now logged in!") +}else { + print("Please check your user name and password and try again.") +} /*: Now that users can log in, they need to be able to search through a list of users to find their friends. This might normally be done by having the user enter a name, and then looping through all user names to see if a user name contains the search term entered. You'll learn about loops later, so for now you'll just work through one cycle of that. Imagine you are searching for a friend whose user name is StepChallenger. You enter "step" into a search bar and the app begins to search. When the app comes to the user name "stepchallenger," it checks to see if "StepChallenger" contains "step." @@ -20,6 +25,9 @@ import Foundation let userName = "StepChallenger" let searchName = "step" +if userName.lowercased().contains(searchName){ + print("\(userName) matches \(searchName) search" ) +} /*: From 464ad8319b8bd59d55b74bc5cc992f3ade84210d Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:44:21 +0200 Subject: [PATCH 06/15] Done functions --- .../Contents.swift | 33 +++++++++++++++++- .../Contents.swift | 31 ++++++++++++++++- .../Contents.swift | 19 ++++++++--- .../Contents.swift | 34 ++++++++++++++++++- .../Contents.swift | 9 ++++- .../Contents.swift | 25 +++++++++++--- 6 files changed, 139 insertions(+), 12 deletions(-) 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..304fa45 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,42 @@ Write a function called `introduceMyself` that prints a brief introduction of yourself. Call the function and observe the printout. */ +func introduceMyself(){ + print("Hi, my name is Samuel from Provo, Utah and I'm 25") +} - +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. */ +func magicEightBall(){ + + let randomNum = Int.random(in: 0...4) + switch randomNum { + case 0: + print("Maybe") + case 1: + print("I don't think so") + case 2: + print("Certainly") + case 3: + print("Who are you asking?") + case 4: + print("No") + default: + print("Random space-time error") + } +} + +magicEightBall() +magicEightBall() +magicEightBall() +magicEightBall() +//: page 1 of 6 | [Next: App Exercise - A Functioning App](@next) + +//: page 1 of 6 | [Next: App Exercise - A Functioning App](@next) + +//: page 1 of 6 | [Next: App Exercise - A Functioning App](@next) //: 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..f3e442d 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,41 @@ 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) +} - +incrementSteps() +incrementSteps() +incrementSteps() +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 +func progressUpdate(){ + let progress = Double(steps)/Double(goal) * 100.0 + if progress < 10{ + print("You're off to a good start.") + }else if progress < 50 { + print("You're almost halfway there!") + }else if progress < 90 { + print("You're over halfway there!") + }else if steps < goal { + print("You're almost there!") + }else{ + print("You beat your goal!") + } + +} +progressUpdate() +steps = 5000 +progressUpdate() +steps = 9500 +progressUpdate() +steps = 11000 +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..4be49d0 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,27 @@ 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(_ first: Int, and: Int){ + let rv = first + and - 2 + print(rv) +} - +almostAddition(8, and: 97) /*: 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(_ first: Double, by second: Double){ + let rv = first*second + print(rv) +} +multiply(3.5, by: 2) //: [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..31131e3 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,43 @@ 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 progress = Double(steps)/Double(goal) * 100.0 + if progress < 10{ + print("You're off to a good start.") + }else if progress < 50 { + print("You're almost halfway there!") + }else if progress < 90 { + print("You're over halfway there!") + }else if steps < goal { + print("You're almost there!") + }else{ + print("You beat your goal!") + } + +} +progressUpdate(steps: 900, goal: 10000) +progressUpdate(steps: 4900, goal: 10000) +progressUpdate(steps: 8500, goal: 10000) +progressUpdate(steps: 9000, goal: 10000) +progressUpdate(steps: 11000, goal: 10000) /*: 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 pace = currentTime/currentDistance + let finishTime = totalDistance * pace + + if finishTime > goalTime { + print("You've got to push it just a bit harder!") + }else{ + print("Keep it up!") + } +} +pacing(currentDistance: 1000, totalDistance: 3000, currentTime: 60, goalTime: 180) +pacing(currentDistance: 1000, totalDistance: 3000, currentTime: 60, goalTime: 150) //: [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..19e1a34 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,18 @@ 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("John")) /*: 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 almostMultiply(_ first: Int, by second: Int) -> Int { + return first*second + 2 +} +print(almostMultiply(3, by: 2)) //: [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..578ac65 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,30 @@ 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 +{ + let pace = currentTime/currentDistance + + return totalDistance * pace +} + +print(calculatePace(currentDistance: 1000, totalDistance: 2000, currentTime: 120)) /*: 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 finishTime = calculatePace(currentDistance: currentDistance, totalDistance: totalDistance, currentTime: currentTime) + + if finishTime > goalTime { + return "You've got to push it just a bit harder!" + } + return "Keep it up!" +} + +print(pacing(currentDistance: 1000, totalDistance: 3000, currentTime: 60, goalTime: 180)) +print(pacing(currentDistance: 1000, totalDistance: 3000, currentTime: 60, goalTime: 170)) +//print(pacing(currentDistance: 1000, totalDistance: 3000, currentTime: 60, goalTime: 180)) /*: _Copyright © 2018 Apple Inc._ From 71ae4ab21fa16174bc1ad47bf169e1daf699d9c3 Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:44:40 +0200 Subject: [PATCH 07/15] Done structures --- .../Contents.swift | 38 ++++++++++++--- .../Contents.swift | 11 ++++- .../Contents.swift | 18 +++++-- .../Contents.swift | 48 +++++++++++++++---- .../Contents.swift | 41 ++++++++++++---- .../Contents.swift | 16 +++++++ .../Contents.swift | 16 +++++++ .../Contents.swift | 30 +++++++++++- .../Contents.swift | 19 +++++++- .../Contents.swift | 12 ++++- 10 files changed, 214 insertions(+), 35 deletions(-) diff --git a/Lab - Structures.playground/Pages/1. Exercise - Structs, Instances, and Default Values.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/1. Exercise - Structs, Instances, and Default Values.xcplaygroundpage/Contents.swift index 61fd1f3..8342824 100644 --- a/Lab - Structures.playground/Pages/1. Exercise - Structs, Instances, and Default Values.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/1. Exercise - Structs, Instances, and Default Values.xcplaygroundpage/Contents.swift @@ -3,26 +3,52 @@ Imagine you are creating an app that will monitor location. Create a `GPS` struct with two variable properties, `latitude` and `longitude`, both with default values of 0.0. */ - +struct GPS{ + var latitude: Double = 0.0 + var longitude: Double = 0.0 +} /*: Create a variable instance of `GPS` called `somePlace`. It should be initialized without supplying any arguments. Print out the latitude and longitude of `somePlace`, which should be 0.0 for both. */ - - +var somePlace = GPS() +print(somePlace.latitude) +print(somePlace.longitude) /*: Change `somePlace`'s latitude to 51.514004, and the longitude to 0.125226, then print the updated values. */ - - +somePlace.latitude = 51.514004 +somePlace.longitude = 0.125226 +print(somePlace.latitude) +print(somePlace.longitude) /*: Now imagine you are making a social app for sharing your favorite books. Create a `Book` struct with four variable properties: `title`, `author`, `pages`, and `price`. The default values for both `title` and `author` should be an empty string. `pages` should default to 0, and `price` should default to 0.0. */ - +struct Book{ + var title: String = "" + var author: String = "" + var pages: Int = 0 + var price: Double = 0.0 +} /*: Create a variable instance of `Book` called `favoriteBook` without supplying any arguments. Print out the title of `favoriteBook`. Does it currently reflect the title of your favorite book? Probably not. Change all four properties of `favoriteBook` to reflect your favorite book. Then, using the properties of `favoriteBook`, print out facts about the book. */ +var favoriteBook = Book() +print(favoriteBook.title) +print(favoriteBook.author) +print(favoriteBook.pages) +print(favoriteBook.price) + +favoriteBook.title = "The Wind in the Willows" +favoriteBook.author = "Kenneth Grahame" +favoriteBook.pages = 200 +favoriteBook.price = 20 + +print(favoriteBook.title) +print(favoriteBook.author) +print(favoriteBook.pages) +print(favoriteBook.price) //: page 1 of 10 | [Next: App Exercise - Workout Tracking](@next) diff --git a/Lab - Structures.playground/Pages/10. App Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/10. App Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift index 159bdcc..aa7fe9d 100644 --- a/Lab - Structures.playground/Pages/10. App Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/10. App Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift @@ -10,15 +10,22 @@ Call the method from outside of the struct and print the result to ensure that it works properly. */ struct RunningWorkout { + static var meterInFeet = 3.28084 + static var mileInMeters = 1600.0 + var distance: Double var time: Double var elevation: Double + + static func mileTimeFor(distance: Double, time: Double) -> Double { + let miles = distance / 1600.0 + return miles/time + } } /*: It may be helpful to have a few type properties on `RunningWorkout` representing unit conversions (i.e. meters to mile, feet to meters, etc.). Go back and add a type property for `meterInFeet` and assign it 3.28084. Then add a type property for `mileInMeters` and assign it 1600.0. Print both of these values below. */ - - +print("meterInFeet: \(RunningWorkout.meterInFeet) mileInMeters: \(RunningWorkout.mileInMeters)") /*: _Copyright © 2018 Apple Inc._ diff --git a/Lab - Structures.playground/Pages/2. App Exercise - Workout Tracking.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/2. App Exercise - Workout Tracking.xcplaygroundpage/Contents.swift index 87c64af..a6b133f 100644 --- a/Lab - Structures.playground/Pages/2. App Exercise - Workout Tracking.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/2. App Exercise - Workout Tracking.xcplaygroundpage/Contents.swift @@ -7,16 +7,28 @@ Create a `RunningWorkout` struct. It should have variables properties for `distance`, `time`, and `elevation`. All three properties should have default values of 0.0. */ - - +struct RunningWorkout{ + var distance: Double = 0.0 + var time: Double = 0.0 + var elevation: Double = 0.0 +} /*: Create a variable instance of `RunningWorkout` called `firstRun` without supplying any arguments. Print out all three properties of `firstRun`. This is a good example of when using default values is appropriate, seeing as all running workouts start with a distance, time, and elevation change of 0. */ - +var firstRun = RunningWorkout() +print(firstRun.distance) +print(firstRun.time) +print(firstRun.elevation) /*: Now imagine that throughout the course of the run, you go a distance of 2,396 meters in 15.3 minutes, and gain 94 meters of elevation. Update the values of `firstRun`'s properties accordingly. Print a statement about your run using the values of each property. */ +firstRun.distance = 2396 +firstRun.time = 15.3 +firstRun.elevation = 94 +print(firstRun.distance) +print(firstRun.time) +print(firstRun.elevation) //: [Previous](@previous) | page 2 of 10 | [Next: Exercise - Memberwise and Custom Initializers](@next) diff --git a/Lab - Structures.playground/Pages/3. Exercise - Memberwise and Custom Initializers.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/3. Exercise - Memberwise and Custom Initializers.xcplaygroundpage/Contents.swift index 6afc9c6..6827326 100644 --- a/Lab - Structures.playground/Pages/3. Exercise - Memberwise and Custom Initializers.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/3. Exercise - Memberwise and Custom Initializers.xcplaygroundpage/Contents.swift @@ -3,18 +3,32 @@ If you completed the exercise Structs, Instances, and Default Values, you created a `GPS` struct with default values for properties of `latitude` and `longitude`. Create your `GPS` struct again, but this time do not provide default values. Both properties should be of type `Double`. */ - +struct GPS{ + var latitude: Double + var longitude: Double +} /*: Now create a constant instance of `GPS` called `somePlace`, and use the memberwise initializer to set `latitude` to 51.514004, and `longitude` to 0.125226. Print the values of `somePlace`'s properties. */ - - +let somePlace = GPS(latitude: 51.514004, longitude: 0.125226) +print(somePlace.latitude) +print(somePlace.longitude) /*: In Structs, Instance, and Default Values, you also created a `Book` struct with properties `title`, `author`, `pages`, and `price`. Create this struct again without default values. Give each property the appropriate type. Declare your `favoriteBook` instance and pass in the values of your favorite book using the memberwise initializer. Print a statement about your favorite book using `favoriteBook`'s properties. */ +struct Book{ + var title: String + var author: String + var pages: Int + var price: Double +} - +let favoriteBook = Book(title: "The Wind in the Willows", author: "Kenneth Grahame", pages: 200, price: 20) +print(favoriteBook.title) +print(favoriteBook.author) +print(favoriteBook.pages) +print(favoriteBook.price) /*: Make a `Height` struct with two variable properties, `heightInInches` and `heightInCentimeters`. Both should be of type `Double`. @@ -22,16 +36,30 @@ - Example: If you use the initializer for inches to pass in a height of 65, the initializer should set `heightInInches` to 65 and `heightInCentimeters` to 165.1. */ - - +struct Height{ + var heightInInches: Double + var heightInCentimeters: Double + + init(inches: Double){ + self.heightInInches = inches + self.heightInCentimeters = self.heightInInches * 2.54 + } + + init(centimeters: Double){ + self.heightInCentimeters = centimeters + self.heightInInches = self.heightInCentimeters / 2.54 + } +} /*: Now create a variable instance of `Height` called `someonesHeight`. Use the initializer for inches to set the height to 65. Print out the property for height in centimeters and verify that it is equal to 165.1. */ - - +let someonesHeight = Height(inches: 65) +print(someonesHeight.heightInCentimeters) +print(someonesHeight.heightInInches) /*: Now create a variable instance of `Height` called `myHeight` and initialize it with your own height. Verify that both `heightInInches` and `heightInCentimeters` are accurate. */ - - +let myHeight = Height(inches: 72.8) +print(myHeight.heightInCentimeters) +print(myHeight.heightInInches) //: [Previous](@previous) | page 3 of 10 | [Next: App Exercise - Users and Distance](@next) diff --git a/Lab - Structures.playground/Pages/4. App Exercise - Users and Distance.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/4. App Exercise - Users and Distance.xcplaygroundpage/Contents.swift index 751d413..33d7af8 100644 --- a/Lab - Structures.playground/Pages/4. App Exercise - Users and Distance.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/4. App Exercise - Users and Distance.xcplaygroundpage/Contents.swift @@ -5,28 +5,51 @@ For most apps you'll need to have a data structure to hold information about a user. Create a `User` struct that has properties for basic information about a user. At a minimum, it should have properties to represent a user's name, age, height, weight, and activity level. You could do this by having `name` be a `String`, `age` be an `Int`, `height` and `weight` be of type `Double`, and `activityLevel` be an `Int` that will represent a scoring 1-10 of how active they are. Implement this now. */ - +struct User{ + var name: String + var age: Int + var height: Double + var weight: Double + var activityLevel: Int +} /*: Create a variable instance of `User` and call it your name. Use the memberwise initializer to pass in information about yourself. Then print out a description of your `User` instance using the instance's properties. */ - - +var user = User(name: "Samuel", age: 25, height: 185, weight: 80, activityLevel: 0) +print(user.name) +print(user.age) +print(user.height) +print(user.weight) +print(user.activityLevel) /*: In previous app exercises, you've worked with distance in the fitness tracking app example as a simple number. However, distance can be represented using a variety of units of measurement. Create a `Distance` struct that will represent distance in various units of measurement. At a minimum, it should have a `meters` property and a `feet` property. Create a custom initializer corresponding to each property (i.e. if you only have the two properties for meters and feet you will then have two initializers) that will take in a distance in one unit of measurement and assign the correct value to both units of measurements. Hint: *1 meter = 3.28084 feet*. - Example: If you use the initializer for meters and pass in a distance of 1600, the initializer should set `meters` to 1600 and `feet` to 5249.344. */ - - +struct Distance{ + var meters: Double + var feet: Double + + init(feet: Double){ + self.feet = feet + self.meters = feet / 3.28084 + } + + init(meters: Double){ + self.meters = meters + self.feet = meters * 3.28084 + } +} /*: Now create an instance of `Distance` called `mile`. Use the initializer for meters to set the distance to 1600. Print out the property for feet and verify that it is equal to 5249.344. */ - - +let mile = Distance(meters: 1600) +print(mile.feet) /*: Now create another instance of `Distance` and give it some other distance. Ensure that both properties are set correctly. */ - - +let d1 = Distance(feet: 1) +print(d1.meters) +print(d1.feet) //: [Previous](@previous) | page 4 of 10 | [Next: Exercise - Methods](@next) diff --git a/Lab - Structures.playground/Pages/5. Exercise - Methods.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/5. Exercise - Methods.xcplaygroundpage/Contents.swift index d90b425..ad40a0a 100644 --- a/Lab - Structures.playground/Pages/5. Exercise - Methods.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/5. Exercise - Methods.xcplaygroundpage/Contents.swift @@ -8,7 +8,14 @@ struct Book { var author: String var pages: Int var price: Double + + func description(){ + print("title: \(self.title) author: \(self.author) pages: \(self.pages) price: \(self.price)") + } } + +let mybook = Book(title:"The Wind in the Willows", author:"Kenneth Grahame", pages:200, price:20) +mybook.description() /*: A `Post` struct has been created for you below, representing a generic social media post. Add a mutating method on `Post` called `like` that will increment `likes` by one. Then create an instance of `Post` and call `like()` on it. Print out the `likes` property before and after calling the method to see whether or not the value was incremented. */ @@ -16,5 +23,14 @@ struct Post { var message: String var likes: Int var numberOfComments: Int + + mutating func like(){ + self.likes += 1 + } } + +var p = Post(message: "Test message", likes: 1, numberOfComments: 0) +print(p.likes) +p.like() +print(p.likes) //: [Previous](@previous) | page 5 of 10 | [Next: App Exercise - Workout Functions](@next) diff --git a/Lab - Structures.playground/Pages/6. App Exercise - Workout Functions.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/6. App Exercise - Workout Functions.xcplaygroundpage/Contents.swift index 774deca..1298ef6 100644 --- a/Lab - Structures.playground/Pages/6. App Exercise - Workout Functions.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/6. App Exercise - Workout Functions.xcplaygroundpage/Contents.swift @@ -9,12 +9,28 @@ struct RunningWorkout { var distance: Double var time: Double var elevation: Double + + func postWorkoutStats(){ + print("distance: \(self.distance) time: \(self.time) elevation: \(self.elevation)") + } } + +let run = RunningWorkout(distance: 32, time: 100, elevation: 12) +run.postWorkoutStats() /*: A `Steps` struct has been created for you below, representing the day's step-tracking data. It has the goal number of steps for the day and the number of steps taken so far. Create a method on `Steps` called `takeStep` that increments the value of `steps` by one. Then create an instance of `Steps` and call `takeStep()`. Print the value of the instance's `steps` property before and after the method call. */ struct Steps { var steps: Int var goal: Int + + mutating func takeStep(){ + steps += 1 + } } + +var test = Steps(steps: 10, goal: 100) +print(test.steps) +test.takeStep() +print(test.steps) //: [Previous](@previous) | page 6 of 10 | [Next: Exercise - Computed Properties and Property Observers](@next) diff --git a/Lab - Structures.playground/Pages/7. Exercise - Computed Properties and Property Observers.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/7. Exercise - Computed Properties and Property Observers.xcplaygroundpage/Contents.swift index cb8e9f0..de723b3 100644 --- a/Lab - Structures.playground/Pages/7. Exercise - Computed Properties and Property Observers.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/7. Exercise - Computed Properties and Property Observers.xcplaygroundpage/Contents.swift @@ -6,16 +6,37 @@ struct Rectangle { var width: Int var height: Int + + var area: Int { + self.width * self.height + } } + +let test = Rectangle(width: 23, height: 4) +print(test.area) /*: In the `Height` struct below, height is represented in both inches and centimeters. However, if `heightInInches` is changed, `heightInCentimeters` should also adjust to match it. Add a `didSet` to each property that will check if the other property is what it should be, and if not, sets the proper value. If you set the value of the other property even though it already has the right value, you will end up with an infinite loop of each property setting the other. Create an instance of `Height` and then change one of its properties. Print out the other property to ensure that it was adjusted accordingly. */ struct Height { - var heightInInches: Double + var heightInInches: Double { + didSet{ + let newCm = self.heightInInches * 2.54 + if self.heightInCentimeters != newCm { + self.heightInCentimeters = newCm + } + } + } - var heightInCentimeters: Double + var heightInCentimeters: Double { + didSet{ + let newInches = self.heightInCentimeters / 2.54 + if self.heightInInches != newInches { + self.heightInInches = newInches + } + } + } init(heightInInches: Double) { self.heightInInches = heightInInches @@ -27,4 +48,9 @@ struct Height { self.heightInInches = heightInCentimeters/2.54 } } + +var hght = Height(heightInCentimeters: 200) +print(hght.heightInInches) +hght.heightInCentimeters = 300 +print(hght.heightInInches) //: [Previous](@previous) | page 7 of 10 | [Next: App Exercise - Mile Times and Congratulations](@next) diff --git a/Lab - Structures.playground/Pages/8. App Exercise - Mile Times and Congratulations.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/8. App Exercise - Mile Times and Congratulations.xcplaygroundpage/Contents.swift index c53c59b..742f844 100644 --- a/Lab - Structures.playground/Pages/8. App Exercise - Mile Times and Congratulations.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/8. App Exercise - Mile Times and Congratulations.xcplaygroundpage/Contents.swift @@ -11,18 +11,35 @@ struct RunningWorkout { var distance: Double var time: Double var elevation: Double + + var averageMileTime: Double { + let miles = self.distance / 1600.0 + return self.time / miles + } } + +let workout = RunningWorkout(distance: 10, time: 60, elevation: 45) +print(workout.averageMileTime) /*: In other app exercises, you've provided encouraging messages to the user based on how many steps they've completed. A great place to check whether or not you should display something to the user is in a property observer. In the `Steps` struct below, add a `willSet` to the `steps` property that will check if the new value is equal to `goal`, and if it is, prints a congratulatory message. Create an instance of `Steps` where `steps` is 9999 and `goal` is 10000, then call `takeStep()` and see if your message is printed to the console. */ struct Steps { - var steps: Int + var steps: Int { + willSet { + if newValue == self.goal { + print("Congratulations, you've met your goal !") + } + } + } var goal: Int mutating func takeStep() { steps += 1 } } + +var walk = Steps(steps: 9999, goal: 10_000) +walk.takeStep() //: [Previous](@previous) | page 8 of 10 | [Next: Exercise - Type Properties and Methods](@next) diff --git a/Lab - Structures.playground/Pages/9. Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift b/Lab - Structures.playground/Pages/9. Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift index b4c4457..c76b8da 100644 --- a/Lab - Structures.playground/Pages/9. Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift +++ b/Lab - Structures.playground/Pages/9. Exercise - Type Properties and Methods.xcplaygroundpage/Contents.swift @@ -7,12 +7,20 @@ struct User { var userName: String var email: String var age: Int + + static var currentUser: User = User(userName: "Samuel", email: "samuel@hesias.fr", age: 25) + + static func logIn(user: User){ + currentUser = user + print("\(User.currentUser.userName) has logged in") + } } + +print("\(User.currentUser.userName), \(User.currentUser.email), age: \(User.currentUser.age)") /*: There are other properties and actions associated with a `User` struct that might be good candidates for a type property or method. One might be a method for logging in. Go back and create a type method called `logIn(user:)` where `user` is of type `User`. In the body of the method, assign the passed in user to the `currentUser` property, and print out a statement using the user's userName saying that the user has logged in. Below, call the `logIn(user:)` method and pass in a different `User` instance than what you assigned to currentUser above. Observe the printout in the console. */ - - +User.logIn(user: User(userName: "Thomas", email: "thomas@test.com", age: 28)) //: [Previous](@previous) | page 9 of 10 | [Next: App Exercise - Type Properties and Methods](@next) From 832541203c062280963e25d57319593ec772f12c Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:45:00 +0200 Subject: [PATCH 08/15] Done classes --- .../Contents.swift | 35 +++++++++--- .../Contents.swift | 54 ++++++++++++++++--- .../Contents.swift | 28 ++++++++-- .../Contents.swift | 39 +++++++++++--- 4 files changed, 130 insertions(+), 26 deletions(-) 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..e9e6983 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,44 @@ 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: Int = 0 + var position: Int = 0 + + func moveLeft(){ + position -= 1 + } + + func moveRight(){ + position += 1 + } + + func wasHit(){ + self.health -= 5 + if self.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(falcon.position) +falcon.moveLeft() +print(falcon.position) +falcon.moveRight() +print(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..ada16a0 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,59 @@ 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: Int = 5 + + func fire(){ + if self.remainingFirePower > 0 { + self.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(destroyer.position) +destroyer.moveRight() +print(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) +/* falcon is undefined in this page. If it were defined as a Spaceship instance + as in previous page it wouldn't work either: Spaceship type has no "weapon" + member. + */ /*: 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(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) +destroyer.fire() +print(destroyer.remainingFirePower) //: [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..1d0b846 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,16 +39,36 @@ 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: Int = 25 + + override func wasHit() { + if self.shieldStrength > 0 { + shieldStrength -= 5 + }else{ + super.wasHit() + } + } +} +let defender = ShieldedShip() +defender.name = "Defender" +defender.weapon = "Cannon" +defender.moveRight() +print(defender.position) +defender.fire() +print(defender.remainingFirePower) /*: 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`. */ - - +defender.wasHit() +print(defender.shieldStrength) +print(defender.health) /*: When `shieldStrength` is 0, all `wasHit()` does is decrement `health` by 5. That's exactly what the implementation of `wasHit()` on `Spaceship` does! Instead of rewriting that, you can call through to the superclass implementation of `wasHit()`. Go back to your implementation of `wasHit()` on `ShieldedShip` and remove the code where you decrement `health` by 5 and replace it with a call to the superclass' implementation of the method. Call `wasHit()` on `defender`, then print `shieldStrength` and `health`. */ - - +defender.wasHit() +print(defender.shieldStrength) +print(defender.health) //: [Previous](@previous) | page 3 of 4 | [Next: Exercise - Class Memberwise Initializers and References](@next) 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..3a057b2 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(name: String, health: Int, position: Int, weapon: String, remainingFirePower: Int) { + self.weapon = weapon + self.remainingFirePower = remainingFirePower + super.init(name: name, health: health, position: position) + } func fire() { if remainingFirePower > 0 { @@ -40,6 +52,10 @@ class Fighter: Spaceship { class ShieldedShip: Fighter { var shieldStrength: Int + init(name: String, health: Int, position: Int, weapon: String, remainingFirePower: Int, shieldStrength: Int) { + self.shieldStrength = shieldStrength + super.init(name: name, health: health, position: position, weapon: weapon, remainingFirePower: remainingFirePower) + } override func wasHit() { if shieldStrength > 0 { shieldStrength -= 5 @@ -53,27 +69,34 @@ 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: 100, 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(name: "Destroyer", health: 100, position: 0, weapon: "", remainingFirePower: 5) /*: 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(name: "Defender", health: 100, position: 0, weapon: "Cannon", remainingFirePower: 5, shieldStrength: 25) /*: 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(sameShip.position) +print(falcon.position) +sameShip.moveLeft() +print(sameShip.position) +print(falcon.position) +/* Both position changed because sameShape and falcon are both pointers + to the same memory location. If both where structs all values from falcon + would have been copied elsewhere upon affectation and the two variable would + be referencing two different memory location thus changing one wouldn't affect + the other. + */ /*: _Copyright © 2018 Apple Inc._ From 599282ae2d55443058a81fe746bb8f5b58c4e12e Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:45:15 +0200 Subject: [PATCH 09/15] Done collections --- .../Contents.swift | 22 ++++++++-------- .../Contents.swift | 22 +++++++++++----- .../Contents.swift | 25 +++++++++++-------- .../Contents.swift | 20 +++++++++------ 4 files changed, 53 insertions(+), 36 deletions(-) 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..7268928 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,31 @@ 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 += ["Bob", "John", "Thomas", "George"] +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:2) +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 deletedItem = registrationList.removeLast() +print(deletedItem) //: 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..a355922 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,36 @@ 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. */ - +let walkingChallenges = ["Walk 3 miles a day", "Walk 30 miles a week"] +let runningChallanges = ["Run 5 times a week","Run 6 miles"] /*: 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, runningChallanges] +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." */ - - +userChallenges.append("Sample challenge 1") +userChallenges.append("Sample challenge 2") +if userChallenges.isEmpty { + print("Please selected a challenge!") +}else if userChallenges.count == 1 { + print("The challenge you have chosen 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..8a83b0d 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,36 @@ 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 dpm = ["January": 31, "February": 28, "March": 31] +print(dpm) /*: Using subscripting syntax to add April to the collection with a value of 30. Print the dictionary. */ - - +dpm["April"] = 30 +print(dpm) /*: It's a leap year! Update the number of days in February to 29 using the `updateValue(_:, forKey:)` method. Print the dictionary. */ - - +dpm.updateValue(29, forKey: "February") +print(dpm) /*: 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 jdays = dpm["January"] { + print("January has \(jdays) 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"] - +var shapeColors = ["Shapes": shapesArray, "Colors": colorsArray] +print(shapeColors) /*: 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. */ - - +if let colors = shapeColors["Colors"] { + print(colors.last!) +} //: [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..39765ff 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,31 @@ 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 = ["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["Medium"] = 7.5 +paces.updateValue(5.8, forKey: "Fast") +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 selectedPace = paces["Medium"] { + print("Okay! I'll keep you at a \(selectedPace) minute mile pace") +} /*: From 6252cb438398f6eb53f5896c57d182d0251053ad Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:45:31 +0200 Subject: [PATCH 10/15] Done Loops --- .../Contents.swift | 15 ++++++++++----- .../Contents.swift | 8 ++++++-- .../Contents.swift | 6 +++++- .../Contents.swift | 12 ++++++++++-- .../Contents.swift | 16 ++++++++++++++-- .../Contents.swift | 7 ++++++- 6 files changed, 51 insertions(+), 13 deletions(-) diff --git a/Lab - Loops.playground/Pages/1. Exercise - For-In Loops.xcplaygroundpage/Contents.swift b/Lab - Loops.playground/Pages/1. Exercise - For-In Loops.xcplaygroundpage/Contents.swift index a019d00..adffe51 100644 --- a/Lab - Loops.playground/Pages/1. Exercise - For-In Loops.xcplaygroundpage/Contents.swift +++ b/Lab - Loops.playground/Pages/1. Exercise - For-In Loops.xcplaygroundpage/Contents.swift @@ -3,17 +3,22 @@ Create a for-in loop that loops through values 1 to 100, and prints each of the values. */ - - +for value in 1...100 { + print(value) +} /*: Create a for-in loop that loops through each of the characters in the `alphabet` string below, and prints each of the values alongside the index. */ let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - +for (idx, char) in alphabet.enumerated() { + print("#\(idx): \(char)") +} /*: Create a `[String: String]` dictionary, where the keys are names of states and the values are their capitals. Include at least three key/value pairs in your collection, then use a for-in loop to iterate over the pairs and print out the keys and values in a sentence. */ - - +let states = ["Texas" : "Austin", "Utah": "Salt Lake City", "Kansas": "Tokepa"] +for (state, capital) in states { + print("The capital of \(state) is \(capital)") +} //: page 1 of 6 | [Next: App Exercise - Movements](@next) diff --git a/Lab - Loops.playground/Pages/2. App Exercise - Movements.xcplaygroundpage/Contents.swift b/Lab - Loops.playground/Pages/2. App Exercise - Movements.xcplaygroundpage/Contents.swift index 20d0853..99ed396 100644 --- a/Lab - Loops.playground/Pages/2. App Exercise - Movements.xcplaygroundpage/Contents.swift +++ b/Lab - Loops.playground/Pages/2. App Exercise - Movements.xcplaygroundpage/Contents.swift @@ -6,12 +6,16 @@ Suppose your app contains a list of different movements that can be tracked. You want to display each item in the list to the user. Use a for-in loop to loop through `movements` below and print each movement. */ let movements: [String] = ["Walking", "Running", "Swimming", "Cycling", "Skiing", "Climbing"] - +for movement in movements { + print(movement) +} /*: Now suppose your app uses a dictionary to keep track of your average heart rate during each of the movements in `movements`. The keys correspond to the movements listed above, and the values correspond to the average heart rate that your fitness tracker has monitored during the given movement. Loop through `movementHeartRates` below, printing statements telling the user his/her average heart rate during each exercise. */ var movementHeartRates: [String: Int] = ["Walking": 85, "Running": 120, "Swimming": 130, "Cycling": 128, "Skiing": 114, "Climbing": 129] - +for (mov, rate) in movementHeartRates { + print("Your average \(mov) heart rate is: \(rate)") +} //: [Previous](@previous) | page 2 of 6 | [Next: Exercise - While Loops](@next) diff --git a/Lab - Loops.playground/Pages/3. Exercise - While Loops.xcplaygroundpage/Contents.swift b/Lab - Loops.playground/Pages/3. Exercise - While Loops.xcplaygroundpage/Contents.swift index e03b910..330b33b 100644 --- a/Lab - Loops.playground/Pages/3. Exercise - While Loops.xcplaygroundpage/Contents.swift +++ b/Lab - Loops.playground/Pages/3. Exercise - While Loops.xcplaygroundpage/Contents.swift @@ -4,6 +4,10 @@ import Foundation Create a while loop that simulates rolling a 6-sided dice repeatedly until a 1 is rolled. After each roll, print the value. (Hint: use `Int.random(in: 1...6)` to generate a random number between 1 and 6). */ - +var val = 0 +while val != 1 { + val = Int.random(in: 1...6) + print("Rolled a \(val)") +} //: [Previous](@previous) | page 3 of 6 | [Next: App Exercise - While Loops](@next) diff --git a/Lab - Loops.playground/Pages/4. App Exercise - Running Cadence.xcplaygroundpage/Contents.swift b/Lab - Loops.playground/Pages/4. App Exercise - Running Cadence.xcplaygroundpage/Contents.swift index 120197b..ef6dedc 100644 --- a/Lab - Loops.playground/Pages/4. App Exercise - Running Cadence.xcplaygroundpage/Contents.swift +++ b/Lab - Loops.playground/Pages/4. App Exercise - Running Cadence.xcplaygroundpage/Contents.swift @@ -11,11 +11,19 @@ import Foundation let cadence: Double = 180 var testSteps = 0 - +while testSteps < 11 { + print("Take a step") + Thread.sleep(forTimeInterval: 60/cadence) + testSteps += 1 +} /*: Recreate the above cadence example using a repeat-while loop. */ testSteps = 0 - +repeat{ + print("Take a step") + Thread.sleep(forTimeInterval: 60/cadence) + testSteps += 1 +}while testSteps < 11 //: [Previous](@previous) | page 4 of 6 | [Next: Exercise - Control Transfer Statements](@next) diff --git a/Lab - Loops.playground/Pages/5. Exercise - Control Transfer Statements.xcplaygroundpage/Contents.swift b/Lab - Loops.playground/Pages/5. Exercise - Control Transfer Statements.xcplaygroundpage/Contents.swift index 2ece88a..5d0dff6 100644 --- a/Lab - Loops.playground/Pages/5. Exercise - Control Transfer Statements.xcplaygroundpage/Contents.swift +++ b/Lab - Loops.playground/Pages/5. Exercise - Control Transfer Statements.xcplaygroundpage/Contents.swift @@ -4,11 +4,23 @@ Create a for-in loop that will loop through `alphabet`. Inside the loop, print every other letter by continuing to the next iteration if you are on a letter you do not wish to print. (Hint: You can use the `isMultiple(of:)` method on `Int` to only print even indexed characters). */ let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - +for (idx, char) in alphabet.enumerated() { + if !idx.isMultiple(of: 2) { + continue + } + print("#\(idx): \(char)") +} /*: Create a `[String: String]` dictionary where the keys are names of states and the values are their capitals. Include at least three key/value pairs in your collection, with one of them being your home state. Now loop through this dictionary again, printing out the keys and values in a sentence, but add an if statement that will check if the current iteration is your home state. If it is, print("I found my home!") and break out of the loop. */ - +let states = ["Texas" : "Austin", "Utah": "Salt Lake City", "Kansas": "Tokepa"] +for (state, capital) in states { + print("The capital of \(state) is \(capital)") + if state == "Utah" { + print("I found my home!") + break + } +} //: [Previous](@previous) | page 5 of 6 | [Next: App Exercise - Finding Movements](@next) diff --git a/Lab - Loops.playground/Pages/6. App Exercise - Finding Movements.xcplaygroundpage/Contents.swift b/Lab - Loops.playground/Pages/6. App Exercise - Finding Movements.xcplaygroundpage/Contents.swift index 1649e6d..99ecb38 100644 --- a/Lab - Loops.playground/Pages/6. App Exercise - Finding Movements.xcplaygroundpage/Contents.swift +++ b/Lab - Loops.playground/Pages/6. App Exercise - Finding Movements.xcplaygroundpage/Contents.swift @@ -11,7 +11,12 @@ let lowHR = 110 let highHR = 125 var movementHeartRates: [String: Int] = ["Walking": 85, "Running": 120, "Swimming": 130, "Cycling": 128, "Skiing": 114, "Climbing": 129] - +for (activity, rate) in movementHeartRates { + if rate < lowHR || rate > highHR { + continue + } + print("You could go \(activity)") +} /*: From 20664cdeb56386e95b88aede9e7191282357d544 Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:45:44 +0200 Subject: [PATCH 11/15] Done optionals --- .../Contents.swift | 16 +++++++---- .../Contents.swift | 16 +++++++---- .../Contents.swift | 28 +++++++++++++++++-- .../Contents.swift | 14 ++++++++-- .../Contents.swift | 22 ++++++++++++++- .../Contents.swift | 19 +++++++++++-- 6 files changed, 96 insertions(+), 19 deletions(-) diff --git a/Lab - Optionals.playground/Pages/1. Exercise - Optionals.xcplaygroundpage/Contents.swift b/Lab - Optionals.playground/Pages/1. Exercise - Optionals.xcplaygroundpage/Contents.swift index 6a8462d..b9edd37 100644 --- a/Lab - Optionals.playground/Pages/1. Exercise - Optionals.xcplaygroundpage/Contents.swift +++ b/Lab - Optionals.playground/Pages/1. Exercise - Optionals.xcplaygroundpage/Contents.swift @@ -7,23 +7,27 @@ Declare a constant `userInputAge` of type `String` and assign it "34e" to simulate a typo while typing age. Then declare a constant `userAge` of type `Int` and set its value using the `Int` initializer that takes an instance of `String` as input. Pass in `userInputAge` as the argument for the initializer. What error do you get? */ - - +let userInputAge: String = "34" +let userAge: Int? = Int(userInputAge) +//Error: Value of optional type 'int?' must be unwrapped to a value of type 'int' +print(userAge) /*: Go back and change the type of `userAge` to `Int?`, and print the value of `userAge`. Why is `userAge`'s value `nil`? Provide your answer in a comment or print statement below. */ - +// Int(String) returned nil when int encountered a non-digit while parsing the string /*: Now go back and fix the typo on the value of `userInputAge`. Is there anything about the value printed that seems off? Print `userAge` again, but this time unwrap `userAge` using the force unwrap operator. */ - - +//print prints the optional (which in turn prints its value), not directly the wrapped Int. +print(userAge!) /*: Now use optional binding to unwrap `userAge`. If `userAge` has a value, print it to the console. */ - +if let uUserAge = userAge{ + print(uUserAge) +} //: page 1 of 6 | [Next: App Exercise - Finding a Heart Rate](@next) diff --git a/Lab - Optionals.playground/Pages/2. App Exercise - Finding a Heart Rate.xcplaygroundpage/Contents.swift b/Lab - Optionals.playground/Pages/2. App Exercise - Finding a Heart Rate.xcplaygroundpage/Contents.swift index 746b8fc..a6dbab2 100644 --- a/Lab - Optionals.playground/Pages/2. App Exercise - Finding a Heart Rate.xcplaygroundpage/Contents.swift +++ b/Lab - Optionals.playground/Pages/2. App Exercise - Finding a Heart Rate.xcplaygroundpage/Contents.swift @@ -7,13 +7,14 @@ Declare a variable `heartRate` of type `Int?` and set it to `nil`. Print the value. */ - +var heartRate: Int? = nil +print(heartRate) /*: In this example, if the user fixes the positioning of the heart rate monitor, the app may get a proper heart rate reading. Below, update the value of `heartRate` to 74. Print the value. */ - - +heartRate = 74 +print(heartRate) /*: As you've done in other app exercises, create a variable `hrAverage` of type `Int` and use the values stored below and the value of `heartRate` to calculate an average heart rate. */ @@ -22,11 +23,16 @@ let oldHR2 = 76 let oldHR3 = 79 let oldHR4 = 70 +var hrAverage: Int = (oldHR1 + oldHR2 + oldHR3 + oldHR4 + heartRate!)/5 /*: If you didn't unwrap the value of `heartRate`, you've probably noticed that you cannot perform mathematical operations on an optional value. You will first need to unwrap `heartRate`. Safely unwrap the value of `heartRate` using optional binding. If it has a value, calculate the average heart rate using that value and the older heart rates stored above. If it doesn't have a value, calculate the average heart rate using only the older heart rates. In each case, print the value of `hrAverage`. */ - - +if let uHeartReate = heartRate { + hrAverage = (oldHR1 + oldHR2 + oldHR3 + oldHR4 + uHeartReate)/5 +}else { + hrAverage = (oldHR1 + oldHR2 + oldHR3 + oldHR4)/4 +} +print(hrAverage) //: [Previous](@previous) | page 2 of 6 | [Next: Exercise - Functions and Optionals](@next) diff --git a/Lab - Optionals.playground/Pages/3. Exercise - Functions and Optionals.xcplaygroundpage/Contents.swift b/Lab - Optionals.playground/Pages/3. Exercise - Functions and Optionals.xcplaygroundpage/Contents.swift index 798d991..c29fc9a 100644 --- a/Lab - Optionals.playground/Pages/3. Exercise - Functions and Optionals.xcplaygroundpage/Contents.swift +++ b/Lab - Optionals.playground/Pages/3. Exercise - Functions and Optionals.xcplaygroundpage/Contents.swift @@ -3,12 +3,27 @@ If an app asks for a user's age, it may be because the app requires a user to be over a certain age to use some of the services it provides. Write a function called `checkAge` that takes one parameter of type `String`. The function should try to convert this parameter into an `Int` value and then check if the user is over 18 years old. If he/she is old enough, print "Welcome!", otherwise print "Sorry, but you aren't old enough to use our app." If the `String` parameter cannot be converted into an `Int` value, print "Sorry, something went wrong. Can you please re-enter your age?" Call the function and pass in `userInputAge` below as the single parameter. Then call the function and pass in a string that can be converted to an integer. */ -let userInputAge: String = "34e" +let userInputAge: String = "12" +func checkAge(_ age: String) -> Int? { + let iAge: Int? = Int(age) + if let uiAge = iAge { + if uiAge > 18 { + print("Welcome") + }else{ + print("Sorry, but you aren't old enough to use our app.") + } + }else{ + print("Sorry, something went wrong. Can you please re-enter your age?") + } + return iAge +} + +checkAge(userInputAge) /*: Go back and update your function to return the age as an integer. Will your function always return a value? Make sure your return type accurately reflects this. Call the function and print the return value. */ - +print(checkAge(userInputAge)) /*: Imagine you are creating an app for making purchases. Write a function that will take the name of an item for purchase and will return the cost of that item. In the body of the function, check to see if the item is in stock by accessing it in the dictionary `stock`. If it is, return the price of the item by accessing it in the dictionary `prices`. If the item is out of stock, return `nil`. Call the function and pass in a `String` that exists in the dictionaries below. Print the return value. @@ -16,5 +31,14 @@ let userInputAge: String = "34e" var prices = ["Chips": 2.99, "Donuts": 1.89, "Juice": 3.99, "Apple": 0.50, "Banana": 0.25, "Broccoli": 0.99] var stock = ["Chips": 4, "Donuts": 0, "Juice": 12, "Apple": 6, "Banana": 6, "Broccoli": 3] +func getPrice(_ name: String) -> Double?{ + if let nitems = stock[name] { + if nitems > 0 { + return prices[name] + } + } + return nil +} +print(getPrice("Donuts")) //: [Previous](@previous) | page 3 of 6 | [Next: App Exercise - Food Functions](@next) diff --git a/Lab - Optionals.playground/Pages/4. App Exercise - Food Functions .xcplaygroundpage/Contents.swift b/Lab - Optionals.playground/Pages/4. App Exercise - Food Functions .xcplaygroundpage/Contents.swift index 98391a4..67771b6 100644 --- a/Lab - Optionals.playground/Pages/4. App Exercise - Food Functions .xcplaygroundpage/Contents.swift +++ b/Lab - Optionals.playground/Pages/4. App Exercise - Food Functions .xcplaygroundpage/Contents.swift @@ -15,12 +15,22 @@ struct Meal { var meals: [String: Meal] = ["Breakfast": Meal(food: ["Bagel", "Orange Juice", "Egg Whites"], calories: 530)] +func getMeal(_ name: String) -> Meal? { + return meals[name] +} +print(getMeal("Breakfast")) +print(getMeal("Dinner")) /*: iOS comes with a few different APIs for persistence, or saving data. You'll learn more about persistence in another lesson, but for now imagine what an app experience would be like if every time you opened the app all of your data was gone. That would be frustrating, right? Write a function that will check to see if your meal log (a dictionary like that in the previous exercise) is saved to the device. If it is, return the meal log. If it isn't, return an empty dictionary of type `[String: Any]`. The code you should use in this exercise for retrieving something saved to the device is `UserDefaults.standard.dictionary(forKey: "mealLog")`. This code will return an optional `[String: Any]`. If it returns a value, that is your meal log. If it returns `nil`, then no meal log has been saved. Call the function and print the return value. */ - - +func getMealLog() -> [String: Any] { + if let rv = UserDefaults.standard.dictionary(forKey: "mealLog") { + return rv + } + return [String: Any]() +} +print(getMealLog()) //: [Previous](@previous) | page 4 of 6 | [Next: Exercise - Failable Initializers](@next) diff --git a/Lab - Optionals.playground/Pages/5. Exercise - Failable Initializers.xcplaygroundpage/Contents.swift b/Lab - Optionals.playground/Pages/5. Exercise - Failable Initializers.xcplaygroundpage/Contents.swift index 9a056cd..48448fa 100644 --- a/Lab - Optionals.playground/Pages/5. Exercise - Failable Initializers.xcplaygroundpage/Contents.swift +++ b/Lab - Optionals.playground/Pages/5. Exercise - Failable Initializers.xcplaygroundpage/Contents.swift @@ -3,11 +3,31 @@ Create a `Computer` struct with two properties, `ram` and `yearManufactured`, where both parameters are of type `Int`. Create a failable initializer that will only create an instance of `Computer` if `ram` is greater than 0, and if `yearManufactured` is greater than 1970, and less than 2017. */ - +struct Computer{ + var ram: Int + var yearManufactured: Int + + init?(ram: Int, yearManufactured: Int){ + if ram <= 0 || yearManufactured <= 1970 || yearManufactured >= 2017 { + return nil + } + self.ram = ram + self.yearManufactured = yearManufactured + } + +} /*: Create two instances of `Computer?` using the failable initializer. One instance should use values that will have a value within the optional, and the other should result in `nil`. Use if-let syntax to unwrap each of the `Computer?` objects and print the `ram` and `yearManufactured` if the optional contains a value. */ +let c1 = Computer(ram: 256, yearManufactured: 2001) +let c2 = Computer(ram: 4096, yearManufactured: 2018) +if let uc1 = c1 { + print("c1: ram: \(uc1.ram) year:\(uc1.yearManufactured)") +} +if let uc2 = c2 { + print("21: ram: \(uc2.ram) year:\(uc2.yearManufactured)") +} //: [Previous](@previous) | page 5 of 6 | [Next: App Exercise - Workout or Nil](@next) diff --git a/Lab - Optionals.playground/Pages/6. App Exercise - Workout or Nil.xcplaygroundpage/Contents.swift b/Lab - Optionals.playground/Pages/6. App Exercise - Workout or Nil.xcplaygroundpage/Contents.swift index ab9f71e..0ec1481 100644 --- a/Lab - Optionals.playground/Pages/6. App Exercise - Workout or Nil.xcplaygroundpage/Contents.swift +++ b/Lab - Optionals.playground/Pages/6. App Exercise - Workout or Nil.xcplaygroundpage/Contents.swift @@ -9,13 +9,26 @@ Write a failable initializer that takes parameters for your start and end times, and then checks to see if they are fewer than 10 seconds apart. If they are, your initializer should fail. Otherwise, they should set the properties accordingly. */ - +struct Workout{ + var startTime: Double + var endTime: Double + + init?(start: Double, end: Double){ + if(end - start < 10){ + return nil + } + self.startTime = start + self.endTime = end + } +} /*: Try to initialize two instances of a `Workout` object and print each of them. One of them should not be initialized because the start and end times are too close together. The other should successfully initialize a `Workout` object. */ - - +let w1 = Workout.init(start: 0, end: 40) +let w2 = Workout.init(start: 0, end: 2) +print(w1) +print(w2) /*: _Copyright © 2018 Apple Inc._ From 01b1525fb35e0cc64825426531f07d0515a1a8da Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:46:01 +0200 Subject: [PATCH 12/15] Done type casting --- .../Contents.swift | 63 +++++++++++++++++-- .../Contents.swift | 16 ++++- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/Lab - Type Casting.playground/Pages/1. Exercise - Type Casting and Inspection.xcplaygroundpage/Contents.swift b/Lab - Type Casting.playground/Pages/1. Exercise - Type Casting and Inspection.xcplaygroundpage/Contents.swift index 31ebae6..6ffdd42 100644 --- a/Lab - Type Casting.playground/Pages/1. Exercise - Type Casting and Inspection.xcplaygroundpage/Contents.swift +++ b/Lab - Type Casting.playground/Pages/1. Exercise - Type Casting and Inspection.xcplaygroundpage/Contents.swift @@ -3,26 +3,81 @@ Create a collection of type [Any], including a few doubles, integers, strings, and booleans within the collection. Print the contents of the collection. */ - +let myCollection: [Any] = [3.14, 0.69, 1, 2, 4, "foo", "bar", true, false] +print(myCollection) /*: Loop through the collection. For each integer, print "The integer has a value of ", followed by the integer value. Repeat the steps for doubles, strings and booleans. */ +for item in myCollection { + if let myInt = item as? Int { + print("The integer as a value of \(myInt)") + } +} + +for item in myCollection { + if let myDouble = item as? Double { + print("The double as a value of \(myDouble)") + } +} + +for item in myCollection { + if let myString = item as? String { + print("The string as a value of \(myString)") + } +} +for item in myCollection { + if let myBool = item as? Bool { + print("The boolean as a value of \(myBool)") + } +} /*: Create a [String : Any] dictionary, where the values are a mixture of doubles, integers, strings, and booleans. Print the key/value pairs within the collection */ - +let mydict: [String:Any] = ["pi": 3.14, "golden": 1.618, "apples":4, "rice":34, "name":"john", "car":"buick", "on":true, "isDirty":false] +for (key, value) in mydict { + print("\(key): \(value)") +} /*: Create a variable `total` of type `Double` set to 0. Then loop through the dictionary, and add the value of each integer and double to your variable's value. For each string value, add 1 to the total. For each boolean, add 2 to the total if the boolean is `true`, or subtract 3 if it's `false`. Print the value of `total`. */ - +var total: Double = 0 +for (_, value) in mydict { + if let mval = value as? Int { + total += Double(mval) + }else if let mval = value as? Double { + total += mval + }else if value is String { + total += 1 + }else if let mval = value as? Bool { + if mval == true { + total += 2 + }else{ + total -= 3 + } + } +} +print(total) /*: Create a variable `total2` of type `Double` set to 0. Loop through the collection again, adding up all the integers and doubles. For each string that you come across during the loop, attempt to convert the string into a number, and add that value to the total. Ignore booleans. Print the total. */ - +var total2: Double = 0 +for (_, value) in mydict { + if let mval = value as? Int { + total2 += Double(mval) + }else if let mval = value as? Double { + total2 += mval + }else if let mval = value as? String { + let dval = Double(mval) + if let umval = dval{ + total2 += umval + } + } +} +print(total2) //: page 1 of 2 | [Next: App Exercise - Workout Types](@next) diff --git a/Lab - Type Casting.playground/Pages/2. App Exercise - Workout Types.xcplaygroundpage/Contents.swift b/Lab - Type Casting.playground/Pages/2. App Exercise - Workout Types.xcplaygroundpage/Contents.swift index ae7131a..8da5cf9 100644 --- a/Lab - Type Casting.playground/Pages/2. App Exercise - Workout Types.xcplaygroundpage/Contents.swift +++ b/Lab - Type Casting.playground/Pages/2. App Exercise - Workout Types.xcplaygroundpage/Contents.swift @@ -45,13 +45,25 @@ var workouts: [Workout] = [ /*: Write simple functions called `describeRun(runningWorkout:)` and `describeSwim(swimmingWorkout:)` that take a `Run` object and a `Swim` object, respectively. Neither should return values. Each function should print a description of the workout, including the run's cadence or the swim's stroke. Time is represented in seconds, distance is represented in meters, and cadence is represented in steps per minute. */ +func describeRun(runningWorkout: Run){ + print("Running time: \(runningWorkout.time) seconds distance: \(runningWorkout.distance) meters cadence: \(runningWorkout.cadence)") +} +func describeSwim(swimmingWorkout: Swim){ + print("Swimming time: \(swimmingWorkout.time) seconds distance: \(swimmingWorkout.distance) meters stroke: \(swimmingWorkout.stroke)") +} /*: Now loop through each workout in `workouts` and, using type casting, call either `describeRun(runningWorkout:)` or `describeSwim(swimmingWorkout:)` on each. Observe what is printed to the console. */ - - +for workout in workouts { + if let swim = workout as? Swim { + describeSwim(swimmingWorkout: swim) + } + if let run = workout as? Run { + describeRun(runningWorkout: run) + } +} /*: _Copyright © 2018 Apple Inc._ From 63bff999f4c2a10ede6c0d6e19a0c3740d110be8 Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:46:22 +0200 Subject: [PATCH 13/15] Done guard --- .../Contents.swift | 32 +++++++++++++---- .../Contents.swift | 36 +++++++++++++++---- 2 files changed, 56 insertions(+), 12 deletions(-) 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..8267d82 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,24 @@ 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 +} +print(calculateArea(x: 2.0, y: 4.0)) +print(calculateArea(x: -2.0, y: 4.0)) /*: 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(x: Int?, y: Int?) -> Int? { + guard let ux = x, let uy = y else {return nil} + + return ux+uy +} - +print(add(x:1, y:2)) +print(add(x:1, y:nil)) /*: 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 +41,19 @@ firstNameTextField.text = "Jonathan" lastNameTextField.text = "Sanders" ageTextField.text = "28" - +func createUser() -> User? { + guard let ufn = firstNameTextField.text, + let uln = lastNameTextField.text, + let uage = ageTextField.text else{ + return nil + } + return User(firstName: ufn, lastName: uln, age: uage) +} /*: 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 rv = createUser() +if let urv = rv { + print("firstName: \(urv.firstName) lastName: \(urv.lastName) age: \(urv.age)") +} //: 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..56837e9 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,8 +10,21 @@ 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?(start: Double, end: Double){ + guard (end - start > 10) else {return nil} + self.startTime = start + self.endTime = end + } +} - +let w1 = Workout.init(start: 0, end: 40) +let w2 = Workout.init(start: 0, end: 2) +print(w1) +print(w2) /*: 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. @@ -26,14 +39,25 @@ let foodTextField = UITextField() let caloriesTextField = UITextField() foodTextField.text = "Banana" -caloriesTextField.text = "23" - - +caloriesTextField.text = "23e" + +func logFood() -> Food? { + guard let uft = foodTextField.text, + let ucal = caloriesTextField.text, + let uical = Int(ucal) else { + return nil + } + return Food(name: uft, calories: uical) +} /*: 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 ufood = logFood(){ + print("name: \(ufood.name), calories: \(ufood.calories)") +} +/*If the calories string can't be parsed into a number, the guard fails, and ufood can't be unwrapped + thus nothing is printed + */ /*: _Copyright © 2018 Apple Inc._ From de7ce902e831299cdf7da6665497c7563b5716ca Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:46:34 +0200 Subject: [PATCH 14/15] Done scope --- .../Contents.swift | 24 ++++++++++++++--- .../Contents.swift | 27 ++++++++++++++++--- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/Lab - Scope.playground/Pages/1. Exercise - Scope.xcplaygroundpage/Contents.swift b/Lab - Scope.playground/Pages/1. Exercise - Scope.xcplaygroundpage/Contents.swift index fb002fb..0559c6f 100644 --- a/Lab - Scope.playground/Pages/1. Exercise - Scope.xcplaygroundpage/Contents.swift +++ b/Lab - Scope.playground/Pages/1. Exercise - Scope.xcplaygroundpage/Contents.swift @@ -8,7 +8,7 @@ for _ in 0..<10 { print("The value of foo is \(foo)") } //print("The value of foo is \(foo)") - +/*line 10 references a symbol (foo) that does only exists in scope from lines 7 to 8*/ /*: Using a comment or print statement, describe why both print statements below compile when similar-looking code did not compile above. In what scope is `x` defined, and in what scope is it modified? In contrast, in what scope is `foo` defined and used? @@ -19,17 +19,35 @@ for _ in 0..<10 { print("The value of x is \(x)") } print("The final value of x is \(x)") - +/*x exists in the global scope and thus can be referenced from anywhere. It is created in global scope, modified and read + in the for{} scope and printed again in the global scope. + foo was only defined in the for{} scope with an incorrect access in global scope. + */ /*: In the body of the function `greeting` below, use variable shadowing when unwrapping `greeting`. If `greeting` is successfully unwrapped, print a statement that uses the given greeting to greet the given name (i.e. if `greeting` successfully unwraps to have the value "Hi there" and `name` is `Sara`, print "Hi there, Sara."). Otherwise, use "Hello" to print a statement greeting the given name. Call the function twice, once passing in a value for greeting, and once passing in `nil`. */ func greeting(greeting: String?, name: String) { + let greeting = greeting != nil ? greeting! : "Hello" + print("\(greeting) \(name)") } + +greeting(greeting: "Hi there", name: "Sara") +greeting(greeting: nil, name: "Sara") /*: Create a class called `Car`. It should have properties for `make`, `model`, and `year` that are of type `String`, `String`, and `Int`, respectively. Since this is a class, you'll need to write your own memberwise initializer. Use shadowing when naming parameters in your initializer. */ - +class Car{ + var make: String + var model: String + var year: Int + + init(make: String, model: String, year: Int){ + self.make = make + self.model = model + self.year = year + } +} //: page 1 of 2 | [Next: App Exercise - Step Competition](@next) diff --git a/Lab - Scope.playground/Pages/2. App Exercise - Step Competition.xcplaygroundpage/Contents.swift b/Lab - Scope.playground/Pages/2. App Exercise - Step Competition.xcplaygroundpage/Contents.swift index a4c5c73..f31644d 100644 --- a/Lab - Scope.playground/Pages/2. App Exercise - Step Competition.xcplaygroundpage/Contents.swift +++ b/Lab - Scope.playground/Pages/2. App Exercise - Step Competition.xcplaygroundpage/Contents.swift @@ -8,6 +8,20 @@ struct User { var name: String var stepsToday: Int + + init(name: String, stepsToday: Int){ + self.name = name + self.stepsToday = stepsToday + } + + init?(name: String?, stepsToday: Int?){ + guard let name = name, + let stepsToday = stepsToday else { + return nil + } + self.name = name + self.stepsToday = stepsToday + } } let stepMaster = User(name: "StepMaster", stepsToday: 8394) @@ -24,8 +38,8 @@ func getWinner(competitors: [User]) -> User? { var topCompetitor: User? for competitor in competitors { - if let topCompetitor = topCompetitor { - if competitor.stepsToday > topCompetitor.stepsToday { + if let utopCompetitor = topCompetitor { + if competitor.stepsToday > utopCompetitor.stepsToday { topCompetitor = competitor } } else { @@ -34,14 +48,21 @@ func getWinner(competitors: [User]) -> User? { } return topCompetitor } + +let rv = getWinner(competitors: competitors) +if let urv = rv { + print(urv.name) +} /*: Write a memberwise initializer inside the `User` struct above that uses variable shadowing for naming the parameters of the initializer. */ - +print(User(name: "Thomas", stepsToday: 6_000)) /*: Now write a failable initializer inside the `User` struct above that takes parameters `name` and `stepsToday` as an optional `String` and `Int`, respectively. The initializer should return `nil` if either of the parameters are `nil`. Use variable shadowing when unwrapping the two parameters. */ +print(User(name: "Benjamin", stepsToday: 6_400)) +print(User(name: "John", stepsToday: nil)) /*: From 146caa7df2d0340338e74bd4a6b2ac6b83e4a47c Mon Sep 17 00:00:00 2001 From: samuel Date: Sun, 20 Jun 2021 14:46:50 +0200 Subject: [PATCH 15/15] Done enumerations --- .../Contents.swift | 40 ++++++++++++++----- .../Contents.swift | 36 ++++++++++++++--- 2 files changed, 60 insertions(+), 16 deletions(-) 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..9c5f017 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,51 @@ Define a `Suit` enum with four possible cases: `clubs`, `spades`, `diamonds`, and `hearts`. */ - +enum Suit {case clubs, spades, diamonds, 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(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 +print(cardInHand) /*: 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 fortune(cardSuit: Suit) { + switch cardSuit { + case .clubs: + print("Luck favors the lucky.") + case .spades: + print("Beware of pointy pin.") + case .diamonds: + print("Big girls need big diamonds.") + case .hearts: + print("You will soon find what you seek.") + } +} + +fortune(cardSuit: Suit.clubs) +fortune(cardSuit: Suit.diamonds) +fortune(cardSuit: Suit.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, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king} + var suit: Suit + 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 c1 = Card(suit: Suit.clubs, value: .four) +print("c1: \(c1.suit) \(c1.value)") +let c2 = Card(suit: Suit.diamonds, value: .ace) +print("c2: \(c2.suit) \(c2.value)") //: page 1 of 2 | [Next: App Exercise - Swimming Workouts](@next) diff --git a/Lab - Enumerations.playground/Pages/2. App Exercise - Swimming Workouts.xcplaygroundpage/Contents.swift b/Lab - Enumerations.playground/Pages/2. App Exercise - Swimming Workouts.xcplaygroundpage/Contents.swift index de34f32..87b7685 100644 --- a/Lab - Enumerations.playground/Pages/2. App Exercise - Swimming Workouts.xcplaygroundpage/Contents.swift +++ b/Lab - Enumerations.playground/Pages/2. App Exercise - Swimming Workouts.xcplaygroundpage/Contents.swift @@ -5,13 +5,35 @@ Previous app exercises have introduced the idea that your fitness tracking app may allow users to track swimming workouts. Create a `SwimmingWorkout` struct below with properties for `distance`, `time`, and `stroke`. `distance` and `time` should be of type `Double` and will represent distance in meters and time in seconds, and `stroke` should be of type `String`. */ - - +struct SwimmingWorkout{ + enum Stroke {case freestyle, butterfly, backstroke, breaststroke} + var distance: Double + var time: Double + var stroke: Stroke + + static var freestyleWorkouts = [SwimmingWorkout]() + static var butterflyWorkouts = [SwimmingWorkout]() + static var backstrokeWorkouts = [SwimmingWorkout]() + static var breaststrokeWorkouts = [SwimmingWorkout]() + + func save(){ + switch self.stroke { + case .freestyle: + SwimmingWorkout.freestyleWorkouts.append(self) + case .butterfly: + SwimmingWorkout.butterflyWorkouts.append(self) + case .backstroke: + SwimmingWorkout.backstrokeWorkouts.append(self) + case .breaststroke: + SwimmingWorkout.breaststrokeWorkouts.append(self) + } + } +} /*: Allowing `stroke` to be of type `String` isn't very type-safe. Inside the `SwimmingWorkout` struct, create an enum called `Stroke` that has cases for `freestyle`, `butterfly`, `backstroke`, and `breaststroke`. Change the type of `stroke` from `String` to `Stroke`. Create two instances of `SwimmingWorkout` objects. */ - - +var sw1 = SwimmingWorkout(distance: 10, time: 100, stroke: .backstroke) +var sw2 = SwimmingWorkout(distance: 20, time: 300, stroke: .freestyle) /*: Now imagine you want to log swimming workouts separately based on the swimming stroke. You might use arrays as static variables on `SwimmingWorkout` for this. Add four static variables, `freestyleWorkouts`, `butterflyWorkouts`, `backstrokeWorkouts`, and `breaststrokeWorkouts`, to `SwimmingWorkout` above. Each should be of type `[SwimmingWorkout]` and should default to empty arrays. */ @@ -20,8 +42,10 @@ /*: Now add an instance method to `SwimmingWorkout` called `save()` that takes no parameters and has no return value. This method will add its instance to the static array on `SwimmingWorkout` that corresponds to its swimming stroke. Inside `save()` write a switch statement that switches on the instance's `stroke` property, and appends `self` to the proper array. Call save on the two instances of `SwimmingWorkout` that you created above, and then print the array(s) to which they should have been added to see if your `save` method works properly. */ - - +sw1.save() +sw2.save() +print(SwimmingWorkout.backstrokeWorkouts) +print(SwimmingWorkout.freestyleWorkouts) /*: _Copyright © 2018 Apple Inc._