Cannot use mutating member on immutable value of type

后端 未结 6 1312
被撕碎了的回忆
被撕碎了的回忆 2021-01-01 09:04

I have following struct:

public protocol SuperModel {
    // empty protocol
}
struct ModelOne: SuperModel {
    struct SubModelOne {
        var someVar: Dou         


        
相关标签:
6条回答
  • 2021-01-01 09:31

    When you apply type casting to value types (such structs), if succeed, you receive immutable copy of requested value:

    (self.data as! ModelOne) // this is copy of data
    

    The only way (as known to me) how you can mutate values that need to be casted - reassign value (as @Sahil Beri pointed you need declare variable):

    func someFunc() {
        if var data = data as? ModelOne {
            data.setSub(ModelOne.SubModelOne(someVar: 2, otherVar: 1))
            self.data = data // you can do this since ModelOne conforms to SuperModel
        }
    }
    
    0 讨论(0)
  • 2021-01-01 09:32

    Problem is that you have declared data as SuperModel but allocate it as ModelOne. Declare data as ModelOne. Then the problem goes away.

    final class SomeClass: SuperClass {
        var data: ModelOne
        init() {
            self.data = ModelOne()
        }
        func someFunc() {
            (self.data).setSub(ModelOne.SubModelOne(someVar: 2, otherVar: 1))
        }
    }
    
    0 讨论(0)
  • 2021-01-01 09:34

    First downcast the self.data to ModelOne then call setSub function

     if var data = self.data as? ModelOne {
       data.setSub(ModelOne.SubModelOne(someVar: 2, othervar: 1))
     }
    
    0 讨论(0)
  • 2021-01-01 09:40

    Use like this,

    struct UserAttributes {
    var name:String?
    var organizationID:String?
    var email:String?
    
    mutating func parseUserAttributes(attribues:[AWSCognitoIdentityProviderAttributeType])->UserAttributes{
    
        for type in attribues{
            if type.name == "name"{
                name = type.value
            }else if(type.name == "family_name"){
                organizationID = type.value
            }else if(type.name == "custom:role_id"){
                role = type.value
            }else if(type.name == "email"){
                email = type.value
             }
    
         }
    
       }  
     }
    

    In some other file call like this,

    var userAttributes = UserAttributes()
    userAttributes = userAttributes.parseUserAttributes(attribues:attributes)
    
    0 讨论(0)
  • 2021-01-01 09:44

    In Swift 3, in my case, I was able to resolve the error just by changing struct to a class object.

    0 讨论(0)
  • 2021-01-01 09:56

    @Shadow of is right. You try to mutate a temporary structure which is impossible and most of the time useless as it will be released once the mutation done. It's in fact a similar issue to trying to modify the return struct of a function. (see answer here : Cannot assign to property: function call returns immutable value)

    0 讨论(0)
提交回复
热议问题