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

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?

3      

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

3      

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.

3      

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.