NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

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 Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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

Reply to this topic…

You need to create an account or log in to reply.

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.