Ray Wenderlich Course Part 10 (up to lesson 91)
Yep - as feared and predicted, this is my first coding session for days! FOUR whole days to be precise! This was totally out of my control - did not get a moment! I'm on the National Express from Corsham to London Victoria, which is technically a three hour journey. I won't code for the entire time but will get at least to the point of Ray's second major project. So first off, it's collections....
Collections
So Arrays, Dictionaries and Sets are the three main types in Swift. I've never actually used sets before. Then it will be onto closures - something I've always found confusing!
Arrays
Each value in an array is an ELEMENT.
They must be of the same type (there is an advanced way apparently!)
They are ordered - each element has an index, starting from 0.
You can use the append method or the += operator to add elements.
The isEmpty method tells us whether it is empty or not. Obviously!
Accessing - you can use .count and .first.
There's also .min and .max.
You can create a variable using the index of the array.
E.g.
firstVale = array[0]
You can use a range with ... between the indexes to return the elements of those indexes.
.contains - another method. Returns a bool.
Basically, there are MANY ways of adding, removing, accessing elements of arrays! Remove, insert, swapAt...lots you can do.
Iterating over the array using the for loop - very useful and powerful!
.enumerated and dropFirst/dropLast are other methods, .prefix and .suffix too. Not going to any more than this for now!
Challenges
I do love these even though they're hard!!
Use index(of:) to determine the position of the element "Dan" in players.
*/
var players = ["Alice", "Bob", "Dan", "Eli", "Frank"]
// TODO: Write solution here
players.index(of: "Dan")
/*:
Write a for-in loop that prints the players' names and scores.
*/
players = ["Anna", "Brian", "Craig", "Dan", "Donna", "Eli", "Franklin"]
let scores = [2, 2, 8, 6, 1, 2, 1]
// TODO: Write solution here
for names in players {
for numbers in scores {
print("\(names) \(numbers)")
}
}
OK - not great! The first one actually wanted an if let statement - that was not clear and mine seemed to work!
The second one is still running, but Ray added in the enumerated and index...again not clear!
Dictionaries
I'm only going to type out things I DON'T already know this time!!
A reminder - anything NOT stored returns nils - so they are optional values.
If you just want the keys printed, you can use the .key method.
OK that was simpler!
### DICTIONARIES
Create a dictionary with the following keys: name, profession, country, state, and city. For the values, put your own name, profession, country, state, and city.
*/
// TODO: Write solution here
var dictionary = ["Name": "Kiran", "Profession": "Beauty Queen", "Country": "UK", "State": "Midlands", "City": "Birmingham"]
/*:
You suddenly decide to move to Albuquerque. Update your city to Albuquerque, your state to New Mexico, and your country to USA.
*/
// TODO: Write solution here
dictionary["City"] = "Albuqerque"
dictionary["State"] = "New Mexico"
dictionary["Country"] = "USA"
///, "State" = "New Mexico", "Country" = "USA"]
/*:
Given a dictionary in the above format, write a function that prints a given person's city and state.
*/
// TODO: Write solution here
func personDetails() {
print("\(dictionary["City"]) and \(dictionary["State"])")
}
personDetails()
Again, tricky stuff!
Right, I've started seeing the solution to the second part and am going to have another go at that....
func personDetails(ofPerson person: [String: String]) {
if let state = person["State"], let city = person["City"] {
print("This person lives in the state of \(state) and the city of \(city)")
}
}
OK, this is a MUCH better function, as you can input the details, rather than have the predetermined dictionary.
Lots of tricky stuff here! I am going to do a bit more then pick this back up tomorrow. Too much in one go not a good idea!
Sets
Syntax is a bit different!
That's all for now!
Closures
These are really cool! You can basically create a method without using names. There a lots of shortcuts that can be used.
You can also create a function that uses a closure within it.
OK, this is getting very complex. Reading the comments I am not alone!
Closures and Collections
So there a lots of closures built in Swift e.g. sorted, filter. Useful stuff.
.map - used to return a certain percentage (or anything else I guess!)
### CLOSURES
Create a constant array called `names` which contains some names as strings (any names will do — make sure there’s more than three though!). Now use `reduce` to create a string which is the concatenation of each name in the array.
*/
// TODO: Write solution here
let names = ["Kiran", "Laura", "Vicki", "Lucy"]
let namesCombined = names.reduce(0) { result, name -> String in
return result + name
}
/*:
Using the same `names` array, first filter the array to contain only names which have more than four characters in them, and then create the same concatenation of names as in the above exercise. (Hint: you can chain these operations together.) */
// TODO: Write solution here
let namesFiltered = names.filter { name -> Bool in
return name.count > 4
}
/*:
Create a constant dictionary called `namesAndAges` which contains some names as strings mapped to ages as integers. Now use `filter` to create a dictionary containing only people under the age of 18. */
// TODO: Write solution here
let namesAndAges = ["Kiran": 24, "Laura": 33, "Lucy": 31, "Mandy": 17]
let namesAndAgesFiltered = namesAndAges.filter { result, pair -> Bool in
return pair < 18
}
/*:
Using the same `namesAndAges` dictionary, filter out the adults (those 18 or older) and then use `map` to convert to an array containing just the names (i.e. drop the ages). */
// TODO: Write solution here
OK these are getting way beyond me! I've given them a go but gave up on the last one as I'm unsure at the moment if ANY of my solutions will work!
OK first one - I Was CLOSE!
let names = ["Kiran", "Laura", "Vicki", "Lucy"]
let namesCombined = names.reduce("") { result, name -> String in
return result + " " + name
}
I had just muddled up the 0 with the initial value as this is a string. I also need an extra " " in for a space in between the names.
Again, close!
let namesFiltered = names.filter { name in
name.count > 4
}
For some reason I didn't need the bool and return parts....For the next part, I would use the second answer, then add on the .reduce method part to get the concatenated string,
let namesAndAgesFiltered = namesAndAges.filter { nameAndAge in
return nameAndAge.value < 18
}
Again, Ray's examples with the different types confused me. Oh well, lots of new concepts and ideas here!
Which Collection to Use?
Ok so basically for what you want to do, different collection types have different speeds for what happens. E.g. with arrays, it takes longer to change items in the middle of it compared to the start.
Didn't get the point of most of this to be honest!
Strings
So a string is technically a collection - like a collection of characters!
You can't use the index value like you can with arrays.
Each character has a 'character set'.
E.g. cafe has 99, 97, 102 and 101
Each of these have a code point. They have use unicode.
Ctrl, command and space - you can search for and pick out the right special character.
Lots more technical stuff here - not bothering to type it out!
So, that's it! Lots of complicated, difficult concepts to make sense of. Perhaps I've been rushing over the past two hours to make up for lost time in the past few days. I'm not going to go into specifics, as it's disheartening to see how much I really don't know!
HOWEVER, the comments seem to confirm to me that Ray has rushed a lot of his explanations and made it all a bit too technical and difficult to relate to. The plan now is to get Structs and Classes (the next two sections) done tomorrow, so that I can at least begin the next project before I head back to Dubai on the 20th. I've got various other plans, but will certainly fit in time to keep working through the next theoretical bits, then the practical challenge of another app! So this will do for today.
Comments
Post a Comment