NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

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