1

I've got some swift code that looks like this:

class GeoRssItem
{
    var title = ""
    var description = ""
}

In another class I declare a variable of this as:

var currentGeoRssItem : GeoRssItem?    // The current item that we're processing

I allocate this member variable as:

        self.currentGeoRssItem = GeoRssItem();

then when I try to assign a property on the self.currentGeoRssItem Xcode auto completes to this:

        self.currentGeoRssItem.?.description = "test"

Which then fails with a build error as so:

"Expected member name following '.'"

How do I set this property? I've read the docs but they aren't very helpful.

2 Answers 2

1

The question mark is in the wrong place. Should be:

self.currentGeoRssItem?.description = "test"

However you might get: "Cannot assign to the result of this expression". In that case you need to check for nil like this:

if let geoRssItem = self.currentGeoRssItem? {
    geoRssItem.description = "test"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yup; “...you can use optional chaining to access a property on an optional value, and to check if that property access is successful. You cannot, however, set a property’s value through optional chaining.” — The Swift Programming Language, "Optional Chaining".
0

If you want to assert that the value is non-nil, you can do:

self.currentGeoRssItem!.description = "test"

If you want the statement to be a no-op if the variable is nil, then

self.currentGeoRssItem?.description = "test"

1 Comment

The ! works, but using the ? results in the error "Cannot assign to the result of this expression"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.