Skip to content
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 = ""
var health = 0
var position = 0

func moveLeft(){
position -= 1
}
func moveRight(){
position += 1
}
func wasHit(){
health -= 5
if health <= 0{
print("Sorry. Your ship was hit one too many times. Do you want to play again?")
}
}
}

/*:
Create a `let` constant called `falcon` and assign it to an instance of `Spaceship`. After initialization, set `name` to "Falcon".
*/

let falcon = Spaceship()
falcon.name = "Falcon"

/*:
Go back and add a method called `moveLeft()` to the definition of `Spaceship`. This method should adjust the position of the spaceship to the left by one. Add a similar method called `moveRight()` that moves the spaceship to the right. Once these methods exist, use them to move `falcon` to the left twice and to the right once. Print the new position of `falcon` after each change in position.
*/

falcon.moveLeft()
print(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()
print(falcon.health)
//: 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,57 @@ 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 = ""
var remainingFirePower = 5

func fire(){
if remainingFirePower > 0{
remainingFirePower -= 1
}else{
print("You have no more fire power.")
}
}
}

/*:
Create a new instance of `Fighter` called `destroyer`. A `Fighter` will be able to shoot incoming objects to avoid colliding with them. After initialization, set `weapon` to "Laser" and `remainingFirePower` to 10. Note that since `Fighter` inherits from `Spaceship`, it also has properties for `name`, `health`, and `position`, and has methods for `moveLeft()`, `moveRight()`, and `wasHit()` even though you did not specifically add them to the declaration of `Fighter`. Knowing that, set `name` to "Destroyer," print `position`, then call `moveRight()` and print `position` again.
*/


var 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("Because falcon takes properties and methods from Spaceship not Fighter.")

/*:
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()

//: [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,38 @@ class Fighter: Spaceship {
/*:
Define a new class `ShieldedShip` that inherits from `Fighter`. Add a variable property `shieldStrength` that defaults to 25. Create a new instance of `ShieldedShip` called `defender`. Set `name` to "Defender" and `weapon` to "Cannon." Call `moveRight()` and print `position`, then call `fire()` and print `remainingFirePower`.
*/

class ShieldedShip: Fighter{
var shieldStrength = 25

override func wasHit() {
if shieldStrength > 0{
shieldStrength -= 5
}else{
super.wasHit()
}
}
}

var 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 @@ -8,6 +8,11 @@ class Spaceship {
var health: Int
var position: Int

init(n: String, h: Int, p: Int) {
name = n
health = h
position = p
}
func moveLeft() {
position -= 1
}
Expand All @@ -28,6 +33,11 @@ class Fighter: Spaceship {
let weapon: String
var remainingFirePower: Int

init(n: String, h: Int, p: Int, w: String, r: Int) {
self.weapon = w
self.remainingFirePower = r
super.init(n: n, h: h, p: p)
}
func fire() {
if remainingFirePower > 0 {
remainingFirePower -= 1
Expand All @@ -39,6 +49,11 @@ class Fighter: Spaceship {

class ShieldedShip: Fighter {
var shieldStrength: Int

init(n: String, h: Int, p: Int, w: String, r: Int, s: Int) {
shieldStrength = s
super.init(n: n, h: h, p: p, w: w, r: r)
}

override func wasHit() {
if shieldStrength > 0 {
Expand All @@ -53,27 +68,36 @@ 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."
*/

var falcon = Spaceship(n: "Falcon", h: 100, p: 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."
*/

var destroyer = Fighter(n: "Destroyer", h: 100, p: 0, w: "Laser", r: 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."
*/

var defender = ShieldedShip(n: "Defender", h: 100, p: 0, w: "", r: 10, s: 5)

/*:
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 sameShip and falcon are referencing the same instance in memory, so what is done to one will be reflected on the other
with structs, spaceShip would be a copy of falcon, and there will be two space in the memory, one for each
*/
/*:

_Copyright © 2018 Apple Inc._
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,32 @@

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

/*:
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 += ["Ben", "Dean", "Maurice", "Daniel"]

/*:
Use the `insert(_:at:)` method to add `Charlie` into the array as the second element. Print the contents of the collection.
*/

registrationList.insert("Charlie", at: 1)

/*:
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.append("Rebecca")

/*:
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`.
*/
registrationList.removeLast()


//: 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,38 @@

Using arrays of type `String`, create at least two lists, one for walking challenges, and one for running challenges. Each should have at least two challenges and should be initialized using an array literal. Feel free to create more lists for different activities.
*/
var walkingChallanges: [String] = ["Walk 3 miles a day.", "Make 10000 steps."]
var runningChallenges: [String] = ["Run 5 times a week.", "Run for 2 km."]


/*:
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 challanges = [walkingChallanges, runningChallenges]
print(challanges[1][0])

/*:
All of the challenges will reset at the end of the month. Use the `removeAll` to remove everything from `challenges`. Print `challenges`.
*/

challanges.removeAll()
print(challanges)

/*:
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 doneChallanges: [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."
*/

if !doneChallanges.isEmpty{
if doneChallanges.count == 1{
print("The challenge you have chosen is \(doneChallanges[0])")
}else{
print("You have chosen multiple challenges.")
}
}else{
print("DO SOMETHING!!")
}

//: [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,39 @@

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 month = ["January": 31, "February": 28, "March": 31]
print(month)
/*:
Using subscripting syntax to add April to the collection with a value of 30. Print the dictionary.
*/


month["April"] = 30
print(month)
/*:
It's a leap year! Update the number of days in February to 29 using the `updateValue(_:, forKey:)` method. Print the dictionary.
*/

month.updateValue(29, forKey: "February")
print(month)

/*:
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 january = month["January"] {
print("January has \(january) 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 mix = ["Shapes": shapesArray, "Colors": colorsArray]
print(mix)


/*:
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 = mix["Colors"]{
print(colors.last!)
}

//: [Previous](@previous) | page 3 of 4 | [Next: App Exercise - Pacing](@next)
Loading