BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

Error. Project 4, part 1, day 26

Forums > 100 Days of SwiftUI

When pasting in the following code from the instructions:
let now = Date()

let tomorrow = Date().addingTimeInterval(86400)

let range = now...tomorrow

I get the following error message: Cannot use instance member 'now' within property initializer; property initializers run before 'self' is available. And also: Cannot use instance member 'tomorrow' within property initializer; property initializers run before 'self' is available

Why is that?

1      

What you need to do is just put those sentences in a function

1      

You're learning! Great! Use all your tools. Try this in the playground.

import SwiftUI

struct expenseDate {
// simple struct with two properties.
    let rightNow = Date()
    let tomorrow = Date().addingTimeInterval(86_400)
}

let myDate =  expenseDate()     // Create a new expenseDate object

myDate.rightNow    // Ask playgrounds to display the myDate.rightNow property
myDate.tomorrow  // Ask playgrounds to display the myDate.tomorrow property

Do you get errors when you run this in Playground? No? So the problem must be in the next line!

But what's going on here? When Swift tries to create this struct, it does a lot of computing. First and foremost, it sets aside memory for two date objects, now and tomorrow. Then it tries to initialize those two properties, per your instructions.

Change the second date to:

let tomorrow = rightNow.addingTimeInterface(86_400)

And run this again in Playground. Now you'll see an error.

Cannot use instance member 'now' within property initializer; property initializers run before 'self' is available

Why? When you changed the second line, you are asking Swift to USE THE OBJECT'S property (rightNow) before the myDate object has finished initializing.

That is, when you are creating the myDate object, you're asking Swift to provide a value for its rightNow property, but the myDate object doesn't exist at the time you're asking for it.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn 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.