Lynda Course - Swift 5 Essential Thinking (Part 6)
Here we go! A quick session now. Not sure how long I've got but gonna do a bit. A couple more chapters of this course, then will review what else from Lynda is worth looking at. At some point I need to decide if the subscription is worth it.
Start Time - 12:57
6. Classes, Structs and Beyond
So I looked at the initial couple of videos last time about value vs reference types. Now the focus is specifically on classes.
Classes
All this is fine - just a recap -
Start Time - 12:57
6. Classes, Structs and Beyond
So I looked at the initial couple of videos last time about value vs reference types. Now the focus is specifically on classes.
Classes
All this is fine - just a recap -
class Adventurer {
var name: String
var maxHealth: Int
var specialMove: String?
init(name: String, maxHP: Int) {
self.name = name
self.maxHealth = maxHP
}
convenience init(name: String) {
self.init(name: name, maxHP: 100)
}
}
var player1 = Adventurer(name: "Steve", maxHP: 75)
var player2 = Adventurer(name: "Dwayne")
var player3 = player1
So a key point now is that any change to player3 will also happen to player1 (Reference type remember!).
player3.maxHealth = 45
Access Modifiers and Properties
Four levels of access - public, internal, file private and private.
Get and set - within computed properties
A few more bits added to the code -
var healthLost: Int {
return maxHealth - 50
}
fileprivate var health: Int
var Health: Int {
get { return health }
set { if newValue <= 100 {
health = newValue
}
}
}
init(name: String, maxHP: Int) {
self.name = name
self.maxHealth = maxHP
self.health = maxHP
}
convenience init(name: String) {
self.init(name: name, maxHP: 100)
}
So for the above, we have a filerprivate var - that cannot be accessed outside of the class. But it did need intialising.
For the computed properties, one had get/set (Health). The other (healthLost) was read only.
Now a word about type variables - use of static and class keywords.
static var maxActivePlayers = 10
class var credo: String {
return "Defend all my friend!"
}
A couple of notes here - the static var cannot be altered in a subclass. The class one can. You can not access these properties on an object/instance of a class, only the class itself.
Useful for storing variables that are global to a class or struct.
Subclassing In Swift
SO here is the syntax for the init part -
class Ranger: Adventurer {
var classAdvantage: String
init(name: String, advantage: String) {
self.classAdvantage = advantage
super.init(name: name, maxHP: 150)
}
}
I'm going to stop there - saved! Will add to and continue this entry a bit more later so classes are done.
Stopped at 13:23 (26 minutes so far)
OK so I wasn't able to add again that day, I'm doing so the next day - the rest of this chapter before bed!
Start Time - 21:01
OK so I wasn't able to add again that day, I'm doing so the next day - the rest of this chapter before bed!
Start Time - 21:01
struct Level {
let levelID: Int
var levelObjective: [String]
var levelDescription: String {
return "Level ID: \(self.levelID)"
}
init(id: Int, objectives: [String]) {
self.levelID = id
self.levelObjective = objectives
}
func queryObjective() {
for objective in levelObjective {
print("\(objective)")
}
}
mutating func completeObjective(index: Int) {
levelObjective.remove(at: index)
}
}
A key point here is that the struct is a value type. So a copy is made for each instance.
Lots of stuff here. Including optional chaining....
Lots of stuff here. Including optional chaining....
struct Item {
var description: String
var previousOwner: Owner?
}
struct Owner {
var name: String
func returnOwnerInfo() -> String {
return "The owner is: \(name)"
}
}
var questDirectory = [
"Fetch Gemstones": [
"Objective": "Retrieve 5 gemstones",
"Secret": "Complete in under 5 minutes"
],
"Defeat Big Boss": [
"Objective": "Beat the ultimate boss",
"Secret": "Win with 50% health left"
]
]
// Creating the chain
var rareDagger = Item(description: "A rather strange, jagged object", previousOwner: nil)
if let owner = rareDagger.previousOwner?.name {
print("This item used to be owned by \(owner)")
} else {
print("OK so the history is unknown")
}
let daggerOwner = Owner(name: "Roland")
rareDagger.previousOwner = daggerOwner
rareDagger.previousOwner?.name = "The thief"
if let ownerInfo = rareDagger.previousOwner {
print("Here is the info - the name is: \(ownerInfo.name)")
} else {
print("No info")
}
if let gemstoneObjective = questDirectory["Fetch Gemstones"]?["Objective"] {
print("This is the objective: \(gemstoneObjective)")
} else {
print("Objective not found")
}
Right challenge time then bed! This is going to need classes, structs and optional chaining. Cool!
// 1
class Item {
var name: String
var price: Int
var secret: BonusEffect?
// 2
init(name: String, price: Int) {
self.name = name
self.price = price
}
}
// 3
struct BonusEffect {
var bonus: Int
}
// 4
// 5
class Inventory {
var storedItems: [Item]
// 6
init(storedItems: [Item]) {
self.storedItems = storedItems
}
}
// 7
var sword = Item(name: "sword", price: 3)
var pistol = Item(name: "pistol", price: 8)
var extraAttack = BonusEffect(bonus: 2)
pistol.secret = extraAttack
// 8
var weaponsList = Inventory(storedItems: [sword, pistol])
if let weaponFact = pistol.secret {
print("The special fact is \(weaponFact)")
} else {
print("No special fact")
}
All seemed fine - just need to check if I had the right idea about 8!
OK, not quite for 8! Before I see the whole answer, let's just look again....
OK this is it!
var weaponsList = Inventory(storedItems: [sword, pistol])
if let weaponFact = weaponsList.storedItems[0].secret?.bonus {
print("The special fact is \(weaponFact)")
} else {
print("No special fact")
}
Needed a bit of help there - so something to practice is the optional chaining when there are custom types within an array.
Finish Time - 21:54 (1 hour 19 minutes grand total)
So lots of useful stuff about classes and structs. Interestingly, not the usual basics but quite a bit involving optionals. When I've done this course (just one more chapter to go) there is plenty I would like to review and look over.
Comments
Post a Comment