UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 11: Static properities and methods - Review Question #6

Forums > 100 Days of SwiftUI

This question was asked here, but it received no answers.

The answer is supposed to be False since allCats is a constant. However, I changed allCats to a var to see how this would work. I'm having trouble figuring out what is happening in this code block and how I would call/use this.

struct Cat {
    static var allCats = [Cat]()
    init() {
        Cat.allCats.append(self)
    }
    static func chorus() {
        for _ in allCats {
            print("Meow!")
        }
    }
}

Creating an instance of Cat prints out "Meow". But if I don't create an instance of Cat, nothing displays in the console. I don't understand why this is the case.

var catTest = Cat()
Cat.chorus() 

2      

Cat.chorus is a static method so you don't need to create an instance of Cat in order to call it.

Cat.chorus calls upon the static allCats array in order to perform its work.

However, allCats is an empty array (initialized as [Cat]()) until and unless a non-static instance of Cat is created, at which point the init gets called and the new instance is appended to the static allCats array.

You can see this like so:

struct Cat {
    static var allCats = [Cat]()
    init() {
        Cat.allCats.append(self)
    }
    static func chorus() {
        //add a little something to better illustrate what's going on...
        if allCats.isEmpty {
            print("*silence*")
        } else {
            for _ in allCats {
                print("Meow!")
            }
        }
    }
}

//listen for cats...
print(Cat.allCats)
Cat.chorus()
//a cat arrives!
let cat1 = Cat()
print(Cat.allCats)
Cat.chorus()
//another cat arrives!
let cat2 = Cat()
print(Cat.allCats)
Cat.chorus()
//one cat goes home
Cat.allCats.removeLast()
print(Cat.allCats)
Cat.chorus()
//and the other goes home
Cat.allCats.removeLast()
print(Cat.allCats)
Cat.chorus()

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.