TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Why does deinit not get called unless inside a for statement

Forums > Swift

Why does deinit successfully print 3 times inside the for statement but the last 2 lines never reach the deinit method and nothing gets printed?

class Person {
  var name = "John Doe"

  init() {
    print("\(name) is alive!")
  }

  func printGreeting() {
    print("Hello, I'm \(name)")
  }

  deinit {
    print("\(name) is no more!")
  }
}

for _ in 1...3 {
  let person = Person()
  person.printGreeting()
}

let anotherPerson = Person()
anotherPerson.printGreeting()

2      

It's a consequence of how playgrounds work differently than code in a project. See this StackOverflow answer:

Deinit method is never called - Swift playground

2      

That makes sense. Thank you.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.