Gagan_iOS
Gagan_iOS

Reputation: 4060

Cannot assign to value: 'self' is immutable in Swift

I am working on an app where I have to deal with Swift & objective-c both. I have model class 'AccountModel' used in Swift & Objective-C as below

@objc class AccountModel : NSObject {

    @objc var accountNumberString : String
    var accountAliasString : String
    @objc var currentBalanceNumber : Double
    @objc var availableBalanceNumber : Double
    .......
     init?(json: Dictionary<String, AnyObject>) 
     {.....}
 }

Now I have created a protocol as below for MVVM logic

protocol AccountListlViewModel {
    var isTransactionalAccount: Bool { get }
    var isSavingAccount: Bool { get }

    var savingAccountModel : AccountModel {get set}

}

extension AccountModel: AccountListlViewModel {
    var savingAccountModel: AccountModel {
        get {
            return self
        }
        set {
            self = newValue   *//ERROR . Cannot assign to value: 'self' is immutable'*
        }
    }

    var isTransactionalAccount: Bool {
        if self.issuingProductCodeString == account_type_Transactional {
            return true
        }
        return  false
    }

    var isSavingAccount: Bool {
        if self.issuingProductCodeString == account_type_Saving {
            return true
        }
        return  false
    }
}

But i am getting error

'Cannot assign to value: 'self' is immutable'

when I tried to set savingAccountModel in GET SET

I know that If create AccountModel as struct then I am able to do set savingAccountModel but I can't create AccountModel as struct as it is used in Objective-c as well.

Please suggest how can I set the property savingAccountModel. Any idea or suggestion would be great.

Upvotes: 1

Views: 1198

Answers (1)

Mark Thormann
Mark Thormann

Reputation: 2617

Based on the above (accounts can't be both savings and transactional at once), you really should consider inheritance here instead of the protocol/extension such as

class SavingsAccount: AccountModel {
    //Savings specific code and properties
}

class TransactionalAccount: AccountModel {
    //Transactional specific code and properties
}

You could then test for account type several ways. One would be attempting to cast your instance.

if let savingsAccount = account as? SavingsAccount {
    //Do some savings account stuff here
}
//Similar for other account types

Upvotes: 1

Related Questions