提问者:小点点

无法赋值:“self”在Swift中是不可变的


我正在开发一个必须与Swift打交道的应用程序

@objc class AccountModel : NSObject {

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

现在我已经为MVVM逻辑创建了如下协议

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
    }
}

但我得到了错误

'无法赋值:'self'是不可变的'

当我试图在GET中设置savingAccount tModel时SET

我知道如果创建Account tModel作为结构体,那么我可以设置savingAccount tModel,但我不能创建Account tModel作为结构体,因为它也在Objective-c中使用。

请建议我如何设置属性savingAccount tModel。任何想法或建议都很棒。


共1个答案

匿名用户

基于上述(账户不能同时是储蓄和交易),您真的应该在这里考虑继承,而不是协议/扩展,例如

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

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

然后,您可以通过多种方式测试帐户类型。一种是尝试转换您的实例。

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