Lynda Course - Swift 5 Essential Thinking (Part 5)
Right! Back on it after several days away. Still struggling to get into some sort of routine. So I'm glad that I've managed to create a little bit of time now - around 40 minutes. Need to go over some of the last bit on closures before the next section...
Start Time - 17:14
Type Aliasing
OK, it was this bit to go over!
Start Time - 17:14
Type Aliasing
OK, it was this bit to go over!
typealias AttackTuple = (name: String, damage: Int, rechargeable: Bool)
var sunStriker: AttackTuple = ("Bruce", 4, true)
I totally get the benefits of type alias. There is no initial value given to the AttackTuple. But the var of sunStriker does.
func levelUpAttack(baseAttack: AttackTuple) -> AttackTuple {
let increasedAttack: AttackTuple = (baseAttack.name, baseAttack.damage + 10, true)
return increasedAttack
}
levelUpAttack(baseAttack: sunStriker)
An example of how to use the AttackTuple as a type within a function.
Also, the type alias can be used for a closure signature. Like this -
typealias ArrayClosure = ([String]) -> Void
func activeMembers(completion: ArrayClosure) {
completion(partyMembers)
}
Right, challenge time!
Challenge
// 1
typealias Attack = (name: String, damage: Int)
// 2
func attackEnemy(attackLevel: Int) {
print("The level of attack is \(attackLevel)")
}
// 3
func attackEnemy(attackInfo: Attack) -> String {
let attackString = "The enemy is \(attackInfo.name) with a damage level of \(attackInfo.damage)"
return attackString
}
// 4
attackEnemy(attackLevel: 5)
var enemy = Attack (name: "AJ", damage: 10)
attackEnemy(attackInfo: enemy)
// 5
typealias AttackClosure = ([Attack]) -> Void
var testArray: [Attack] = [(name: "Roman", damage: 7), (name: "Seth", damage: 9), (name: "Steve", damage: 5)]
// 6
func fetchPlayerAttacks(info: AttackClosure) {
info(testArray)
}
// 7
fetchPlayerAttacks { (info) in
for (name, damage) in info {
print("Name: \(name), damage: \(damage)")
}
}
Awesome! Nailed all of them. Only thing to change would be in the testArray I don't need to use the parameter names - they will be inferred so could do ("Seth", 9) etc.
Going to start the intro of the next chapter - Chapter 6 - classes, structs and beyond!
Value types. Yes I like the analogy of the sword! So in a shop, you want to buy a sword (of course you do...) and rather than buying the exact one on display, you have a version of that one sold to you. That is value type! They are two separate objects.
Reference types... Avatar example but not as clear.
Key point is deciding in when to use struct or class.
Finish Time - 17:58
So yes! A good session to get my head around the rest of the closure/link to type alias and do the challenge. All done for today. Next time will be all about structs, classes etc.
Comments
Post a Comment