使用 swift 默认交换函数交换自定义 class 对象

swap custom class object with swift default swap function

我想在 swift 5.0

中使用默认交换功能

这是我写的

swap(&buyingCurrencyObj, &sellingCurrencyObj)

哪里

var sellingCurrencyObj = SellingCurrency()
var buyingCurrencyObj = BuyingCurrency()

但是它说

Cannot convert value of type 'SellingCurrency' to expected argument type 'BuyingCurrency'

BuyingCurrency() 和 SellingCurrency() 是我的两个 class,它们具有相同的功能,但参数不同。

open class SellingCurrency {

public init() { }
    public var sellingCurrencyDisplayName:String?
    public var sellingCurrencyActive:Bool?
    public var sellingCurrencyCode:String?
    public var sellingCurrencyTradingPlatformID:String?
    public var sellingCurrencyID:String?
}

open class BuyingCurrency {
public init() { }
    public var buyingCurrencyDisplayName:String?
    public var buyingCurrencyActive:Bool?
    public var buyingCurrencyCode:String?
    public var buyingCurrencyTradingPlatformID:String?
    public var buyingCurrencyID:String?
}

我想交换这两个 class 对象。 如何在自定义 class 对象上使用默认交换函数。

谢谢。

swap 的输入参数类型需要匹配。我建议创建一个通用协议,您的 类 都遵守该协议,然后将您的变量存储为协议。

protocol Currency {
    var displayName: String? { get }
    var active: Bool? { get }
    var currencyCode: String? { get }
    var tradingPlatformID: String? { get }
    var currencyID: String? { get }
}

open class SellingCurrency: Currency {
    public init() { }
    public var displayName: String?
    public var active: Bool?
    public var currencyCode: String?
    public var tradingPlatformID: String?
    public var currencyID: String?
}

open class BuyingCurrency: Currency {
    public init() { }
    public var displayName: String?
    public var active: Bool?
    public var currencyCode: String?
    public var tradingPlatformID: String?
    public var currencyID: String?
}

var buyingCurrency: Currency = BuyingCurrency()
var sellingCurrency: Currency = SellingCurrency()

swap(&buyingCurrency, &sellingCurrency)

对您的代码进行一些一般性改进:

  • 用类型名称作为变量名称前缀没有任何价值,但会使可读性更差,所以我强烈建议不要这样做。
  • 制作一个类型 Optional 的所有属性通常是一个巨大的代码味道 - 只制作属性 Optional,这确实需要 Optional.

由于 SellingCurrencyBuyingCurrency 具有相同类型的数据,您可以简单地创建一个代表它们的单个 class 而不是有 2 个不同的类型,

open class Currency {
    public var displayName:String?
    public var active:Bool?
    public var code:String?
    public var tradingPlatformID:String?
    public var ID:String?
}

现在,制作 2 个 Currency 类型的实例 - 一个用于买入,另一个用于卖出,

var sellingCurrencyObj = Currency()
var buyingCurrencyObj = Currency()

接下来对上述实例使用swap(_:_:)操作,

swap(&sellingCurrencyObj, &buyingCurrencyObj)