Nick Walter Challenges (Part 4)
Yes, here we go - third day of consecutive entries, whoo! I need to ensure that this does not become a habit - being able to code only at the weekend. I must ensure that I code at least on two days out of Sunday to Wednesday. Anyway, back to Nick's challenges. I've loved these so far however they are certainly getting harder. At some point I will have to go through the course content, which is absolutely fine. First off, it will be functions which I'll be fine with. Optionals - definitely something I need more practice with. Let's do it!
The screen shots I took STILL not did not get saved here properly. So back to typing it all until I find another way! This is fine - it's part of the learning process. My new idea is to save a screenshot as usual, THEN save it as a JPEG. We'll see if that does it!
*Delaying start of coding as Xcode is still updating.
Start time - 11:17
Functions
So none of these look hard at all. 1) needs lyrics printed when the function happens - no parameters or returns. 2) has 4 parameters with one as an external name, 3) is easy enough and 4) again should not be a problem.
The screen shots I took STILL not did not get saved here properly. So back to typing it all until I find another way! This is fine - it's part of the learning process. My new idea is to save a screenshot as usual, THEN save it as a JPEG. We'll see if that does it!
*Delaying start of coding as Xcode is still updating.
Start time - 11:17
Functions
So none of these look hard at all. 1) needs lyrics printed when the function happens - no parameters or returns. 2) has 4 parameters with one as an external name, 3) is easy enough and 4) again should not be a problem.
func lyricsPrint() {
print("Sometimes I feel like I don't have a partner")
}
func personDetails(name: String, age: Int, shoeSize: Int, numberOfSiblings siblings: Int) {
print("\(name) is \(age) years old, has a shoe size of \(shoeSize) and has \(siblings) siblings")
}
func squareNumber(number: Int) -> Int {
return number * number
}
let number = squareNumber(number: 6)
func studentScore(name: String, score: Int) -> String {
var grade = ""
switch score {
case 90...100:
grade = "A"
case 80...89:
grade = "B"
case 70...79:
grade = "C"
case 60...69:
grade = "D"
case 50...59:
grade = "E"
default:
grade = "Invalid Grade"
}
return ("With a score of \(score), \(name) got a \(grade) grade in the exam")
}
let gradeString = studentScore(name: "Josh", score: 75)
print(gradeString)
Those were all FUN! I figured with the functions one that a switch statement was best - numbers and cases and all that jazz. Just checking the solutions....
Awesome - smashed it!
One amendment - switch statements use returns too. So it makes more sense of the default to return a separate string to the overall function return.
default:
return "Invalid Grade"
That is optional really - it doesn't really make a difference - the other one is arguable more detailed. Also, I wouldn't want to use return each time for the switch statement, as this would be repetitive code. DRY - Don't Repeat Yourself!
Optionals
I'm going to actually go through these lessons as I need to make them clearer in my mind! THEN I will do the challenges!
let age: Int? = 45
if age == nil {
print("Age has no value")
} else {
print(age)
}
One of the features of the new Xcode (yes it's updated and working!) is that it came up with a yellow error to fix...
print(age as Any)
The 'as Any' is something new and not covered in Nick's 2.0 Swift course.
Nick also shows the safety of this if you've put in the wrong type e.g. a string when you've declared it as an Int optional.
Forced unwrapping - always get told this is best NOT to do. Using the exclamation mark is only when you are 100% certain. OK Nick reinforces this.
The link I can see to real apps is if the contents of a value have to be emptied in some way - resetting a score, or some sort of aspect during a game for example. If that is the case, then storing something as nil is better than receiving the entire aspect. Also, having nil makes it safer as it stops the crashing!
let name: String? = "Josh"
name?.uppercased()
Interesting - something that Nick explains is fixed in the current Swift. Nice.
if let name = name {
print(name)
} else {
print("No name")
}
I've deliberately kept this the same name - the let name as the name optional above. I could have changed this to clarify but it does work!
So this is optional chaining. I know there is a guard let option as well....
OK leaving guard let for now as the syntax seems to have changed!
Right so Nick's Optional stuff was pretty brief. Now on to the challenges!
Optionals Challenges
Here we go! 1) Easy. 2) Trickier but should be fine. 3) I will come back to once I've done 1 and 2...
//1
let robotName: String? = nil
//2
let numberString = "3"
if let number = Int(numberString) {
print(number * number )
} else {
print("Not a valid number!")
}
So far so good!
func detailsOfPerson(name: String, age: Int) -> String? {
if age >= 0 {
return ("The name is \(name) and the age is \(age)")
} else {
return nil
}
}
let chrisCooper = detailsOfPerson(name: "Chris Cooper", age: 45)
print(chrisCooper!)
Right, I started doing an if let, then realised it was only the return (the String) that was an optional. Let's check the solution....
2) Was done a little differently - it was created as an Int(number) rather than me doing the conversion within the if let statement. Still works either way - a bit of an ambiguous instruction Nick!
let chrisCooper = detailsOfPerson(name: "Chris Cooper", age: -9)
print(chrisCooper ?? "Invalid age")
I got all of this - slightly different but totally logical. I've gone on to using the new Xcode suggested fixes where nil is returned (with the -9 used for Chris Cooper). In this, the ?? is the if/let statement/guard statement all in one go. Nice!
Classes and Structures Challenges
For this I'm going straight on to the challenge to see what I can do! Loving the new updated Xcode actually working too! :)
By the way, I've done a screenshot, then inserted them as pictures each time. The first two are JPEGs, this one above is a PNG. We'll see which ones actually get saved! If all of them do, then no converting needed but inserting the pic is a must!
Anyway let's go...
1) That sounds OK. 2) No problem... 3) The function should be OK too. Then 4) is just the case of changing the keyword!
class Microwave {
let power = 4550
let name = "TC 4.5"
let topSpeed = 10
let location = "kitchen"
func microwaveInfo() -> String {
return ("The name of this microwave is \(name), its power is \(power) and it is located in the \(location).")
}
}
let micro1 = Microwave()
print(micro1.microwaveInfo())
So I've done this with values given to each stored property, rather than using initialisers (I can't imagine Nick would have gone onto those so soon!)
For challenge 4 it should just be changing class to struct....Yes! Now let's see the solution....
Yes that's fine - Nick's solution has variable stored properties, which he has then changed after creating an object. I could have done the same but kept them as constants, as I assumed that nothing would need to be changed for this example. The simpler way, which made total sense for the questions!
Finish time - 12:45 (total of 1 hour 29 minutes)
So pretty much an hour and a half of solid coding! Great to go over functions (easy!), learn more about optionals and apply all of that, as well as the class code, which again was no problem for me. Looking ahead, Nick has some stuff on properties, which will be well worth going over, as will initialization. I may do some more today if I get the chance! Also, let's see if those screenshots saved!
Comments
Post a Comment