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

SOLVED: Cannot assign to property because the value being assigned is a let constant

Forums > SwiftUI

In the code snippet below I am trying to assign a value from the array activityDays to a variable and then use that variable on the following line.

However, the line that assigns a value to name won't compile, because activityTypeName is a let constant. I don't understand why that matters?

    init(activityDays: Binding<[ActivityDay]>, action: Binding<ActivityListActions>, tags: [TagSelected]) {

        _activityDays = activityDays
        _action = action
        self.tags = tags

        var activityTypes: [ActivityTypeSelected] = []

        for activity in activityDays {

            var name = activity.activityTypeName // Won't compile because activityTypeName is a let constant - but why should that matter?
            activityTypes.append(ActivityTypeSelected(activityTypeName: name, isSelected: false))

        }

    }

Is this something to do with the parameter being a Binding? I can't even do

print(activity.activityTypeName)

in the loop - it gives me the same error.

2      

Please give us some more code. Without knowing anything about ActivityDay and ActivityTypeSelected, we can't copy/paste your code to reproduce the issue and figure out a solution. (We don't need ActivityListAction or TagSelected because those aren't involved in the problem.)

2      

I think what you need to do is access the wrapped value of the @Binding, you do that by putting an underscore in front of it.

var name = _activity.activityTypeName

2      

An underscore accesses the property wrapper itself, not the wrapped value.

That's why you do this when assigning a Binding parameter to a property:

_activityDays = activityDays

But yeah, accessing the wrapped value solves the error:

for activity in activityDays.wrappedValue {

    var name = activity.activityTypeName
    activityTypes.append(ActivityTypeSelected(activityTypeName: name, isSelected: false))

}

2      

Well, at least I was half-right 😀

2      

Oh. My. Goodness.

Thank you very much!

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.