Store part of an optional path in a reusable variable

Forgive me for the simple ask. I am a beginner and can't seem to find the answer.

I'm using optional chaining to access a nested json object

Text(store.result? ?? "")

I access the first "docs" property in multiple places and would like to use a variable to store the reused first part of the path


...but I can't quite figure out how. I've tried

var firstArticle: NYTSearchResponse? { return result? }

but I get an error "Type of expression is ambiguous without more context".

Can anyone let me how I can store part of an optional chain path in a variable so I can reuse it?

I didn’t fully understood what you are trying to achieve, so let me ask some clarifying questions:

Is firstArticle a property on store?

Do you want to reuse value or a key path? Is store a part of what is being reused or it will be passed from the outside?

Can something be mutated between accesses? When accessing the reused entity after mutation do you want to see old value or new value?

Thanks so much for the response. I figured out what I needed to do. I wanted a computed property to store a reusable json path.

var firstDoc: Doc? { return dataStore.result? }

What I was getting hung up on is the variable type. Originally, I was defining this variable as a NYTSearchResponse type, which is the struct that I use to store the entire json response. But the type needs to match the object found at the end of the path, in this case a Doc.

Thanks again for your response and willingness to help with my beginner problem.

Terms of Service

Privacy Policy

Cookie Policy