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

Watching swift in one hour - question about class refence

Forums > Swift

Please consider the section about deinit and Site:

class Site{
    let id: Int

    init(_ id: Int){
        self.id = id;
        print("init! id: \(id)")
    }

    deinit{
        print("All your DEINIT are belong to us!! id:\(id)")
    }
}

Now Paul made a for-loop where expectedly init and deinit for all created Sites were called.

for i in 42...45{
        let site = Site(i)
    }

However, i tried declaring the object outside the for loop like this:

    var site: Site;
    for i in 51...53{
        site = Site(i)
    }

I expected that the deinit to be called for Sites 51 and 52, but that the site variable would have a value (an object with the id 53) after the loop but if i try to print it like this:

print("what value has Site: (site.id)")

i get an error message about the variable being used before it is initialized?

I don't get this, could someone enlighten me?

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.