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

All playgrounds and reading book done #16

Open
wants to merge 1 commit 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
Binary file added .DS_Store
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,46 @@

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.
*/


print(falcon.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,46 @@ 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.
*/


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.
*/

// falcon is Spaceship, weapon is property of Fighter not Spaceship

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

//: [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 = 25

override func wasHit() {
if 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(weapon: String, remainingFirePower: Int, name: String, health: Int, position: Int) {
self.weapon = weapon
self.remainingFirePower = remainingFirePower
super.init(name: name, health: health, position: position)
}

func fire() {
if remainingFirePower > 0 {
Expand All @@ -39,6 +51,11 @@ class Fighter: Spaceship {

class ShieldedShip: Fighter {
var shieldStrength: Int

init(shieldStrength: Int, weapon: String, remainingFirePower: Int, name: String, health: Int, position: Int) {
self.shieldStrength = shieldStrength
super.init(weapon: weapon, remainingFirePower: remainingFirePower, name: name, health: health, position: position)
}

override func wasHit() {
if shieldStrength > 0 {
Expand All @@ -53,27 +70,35 @@ 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: 50, position: 0)

/*:
Writing initializers for subclasses can get tricky. Your initializer needs to not only set the properties declared on the subclass, but also set all of the uninitialized properties on classes that it inherits from. Go to the declaration of `Fighter` and write an initializer that takes an argument for each property on `Fighter` and for each property on `Spaceship`. Set the properties accordingly. (Hint: you can call through to a superclass' initializer with `super.init` *after* you initialize all of the properties on the subclass).

Then create an instance of `Fighter` below called `destroyer`. Use the memberwise initializer you just created. The ship's name should be "Destroyer."
*/


let destroyer = Fighter(weapon: "Laser", remainingFirePower: 10, name: "Destroyer", health: 50, position: 0)
/*:
Now go add an initializer to `ShieldedShip` that takes an argument for each property on `ShieldedShip`, `Fighter`, and `Spaceship`, and sets the properties accordingly. Remember that you can call through to the initializer on `Fighter` using `super.init`.

Then create an instance of `ShieldedShip` below called `defender`. Use the memberwise initializer you just created. The ship's name should be "Defender."
*/


let defender = ShieldedShip(shieldStrength: 100, weapon: "Cannon", remainingFirePower: 10, name: "Defender", health: 100, position: 0)
/*:
Create a new constant named `sameShip` and set it equal to `falcon`. Print out the position of `sameShip` and `falcon`, then call `moveLeft()` on `sameShip` and print out the position of `sameShip` and `falcon` again. Did both positions change? Why? If both were structs instead of classes, would it be the same? Why or why not? Provide your answer in a comment or print statement below.
*/


let sameShip = falcon
print(falcon.position)
print(sameShip.position)
sameShip.moveLeft()
print(falcon.position)
print(sameShip.position)

//falcon contains memory adress of object so we assign to sameShip this same adress
//so sameShip and falcon are the same object any edit on one will be done one the other
//if it is struct, assign falcon to sameShip just make copy of instance
//edit on one will don't make any change on the other
/*:

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

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 += ["Samy", "Jonh", "Steve", "Franck"]
print(registrationList)
/*:
Use the `insert(_:at:)` method to add `Charlie` into the array as the second element. Print the contents of the collection.
*/


registrationList.insert("Charlie", at: 1)
/*:
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,31 @@

Using arrays of type `String`, create at least two lists, one for walking challenges, and one for running challenges. Each should have at least two challenges and should be initialized using an array literal. Feel free to create more lists for different activities.
*/


var walkingChallenges: [String] = ["Walk 3 miles a day", "Walk up stairs instead of using elevator"]
var runningChallenges: [String] = ["Run 5 days a week", "Run 100 miles in a month"]
/*:
In your app you want to show all of these lists on the same screen grouped into sections. Create a `challenges` array that holds each of the lists you have created (it will be an array of arrays). Using `challenges`, print the first element in the second challenge list.
*/


var challenges = [walkingChallenges, runningChallenges]
print(challenges[1][0])
/*:
All of the challenges will reset at the end of the month. Use the `removeAll` to remove everything from `challenges`. Print `challenges`.
*/


challenges.removeAll()
print(challenges)
/*:
Create a new array of type `String` that will represent challenges a user has committed to instead of available challenges. It can be an empty array or have a few items in it.
*/

var committedChallenges = [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 committedChallenges.isEmpty {
print("commit a challenge first !")
} else if committedChallenges.count == 1 {
print("The challenge you have chosen is \(committedChallenges[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,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 daysNumberInMonths: [String: Int] = ["January": 31, "February": 28, "March": 31]
print(daysNumberInMonths)
/*:
Using subscripting syntax to add April to the collection with a value of 30. Print the dictionary.
*/

daysNumberInMonths["April"] = 30
print(daysNumberInMonths)

/*:
It's a leap year! Update the number of days in February to 29 using the `updateValue(_:, forKey:)` method. Print the dictionary.
*/

daysNumberInMonths.updateValue(29, forKey: "February")

/*:
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 januaryDays = daysNumberInMonths["January"] {
print("January has \(januaryDays) days.")
}

/*:
Given the following arrays, create a new [String : [String]] dictionary. `shapesArray` should use the key "Shapes" and `colorsArray` should use the key "Colors". Print the resulting dictionary.
*/
let shapesArray = ["Circle", "Square", "Triangle"]
let colorsArray = ["Red", "Green", "Blue"]


let shapesColors: [String: [String]] = ["Shapes": shapesArray, "Colors": colorsArray]
print(shapesColors)
/*:
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 = shapesColors["Colors"] {
print(colors.last ?? "No color in colors")
}

//: [Previous](@previous) | page 3 of 4 | [Next: App Exercise - Pacing](@next)
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +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: [String: Double] = ["Easy": 10.0, "Medium": 8.0, "Fast": 6.0]
print(paces)
/*:
Add a new key/value pair to the dictionary. The key should be "Sprint" and the value should be 4.0. Print the dictionary.
*/


paces["Sprint"] = 4.0
print(paces)
/*:
Imagine the user in question gets faster over time and decides to update his/her pacing on runs. Update the values of "Medium" and "Fast" to 7.5 and 5.8, respectively. Print the dictionary.
*/

paces.updateValue(7.5, forKey: "Medium")
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 <INSERT PACE VALUE HERE> minute mile pace."
*/


if let pace = paces["Medium"] {
print("Okay! I'll keep you at a \(pace) minute mile pace.")
}
/*:

_Copyright © 2018 Apple Inc._
Expand Down
Loading