pdrersin
pdrersin

Reputation: 311

Error - Cannot use mutating member on immutable value: function call returns immutable value

So I have this custom struct

public struct Feature {
    var featureID: String = ""
    var featureName: String = ""
    var matchingFieldValue: String = ""

    var polygonCollection =  [MyPolygon]()

    mutating func setFeatureID(featureID: String) {
        self.featureID = featureID
    }

    func getMatchingFieldValue() -> String {
        return matchingFieldValue
    }

    mutating func setMatchingFieldvalue(matchingFieldValue: String) {
        self.matchingFieldValue = matchingFieldValue
    }

    public func getPolygonCollection() -> [MyPolygon] {
         return polygonCollection  
    }  
}

and I am trying to append a polygon to my polygonCollection by calling this function

feature.getPolygonCollection().append(polygon)

but I am getting the error

cannot use mutating member on immutable value: function call returns immutable value

by the way, I am defining the polygon in another class, it is a long class so just put the relevant calling code that gives the error.

All the previously asked ques

I appreciate all the help.

Upvotes: 2

Views: 4608

Answers (1)

vadian
vadian

Reputation: 285064

Due to value semantics getPolygonCollection() returns an immutable copy of polygonCollection. You cannot change it. That's what the error message says.

Add this function in the struct

mutating func add(polygon: MyPolygon) {
    self.polygonCollection.append(polygon)
}

and call it

feature.add(polygon)

Upvotes: 1

Related Questions