Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed the labs #25

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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._
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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 <INSERT CHOSEN CHALLENGE>" 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)
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading