【问题标题】:Cannot assign to value: 'self' is immutable in Swift无法赋值:'self' 在 Swift 中是不可变的
【发布时间】:2019-01-31 14:28:30
【问题描述】:

我正在开发一个应用程序,我必须同时处理 Swift 和 Objective-c。 我在 Swift 和 Objective-C 中使用了模型类“AccountModel”,如下所示

@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 SET 中设置 SavingAccountModel 时

我知道如果将 AccountModel 创建为 struct,那么我可以设置 SavingAccountModel,但我不能像在 Objective-c 中使用的那样将 AccountModel 创建为 struct。

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

【问题讨论】:

  • 因此您希望您的AccountModel 在变量中保存对自身的引用。为什么?
  • 是的,原因是来自服务器的账户有多种类型,我想根据实现的一些逻辑分别存储它们。
  • 您似乎尝试在扩展中定义存储属性。这是不可能的(除非您使用诸如“关联对象”之类的 Objective-C 运行时特性)。 – [swift] extension stored property

标签: swift


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2020-01-28
    相关资源
    最近更新 更多