gpt4 book ai didi

swift - 使用扩展在 Swift 中符合协议(protocol)

转载 作者:可可西里 更新时间:2023-11-01 00:56:02 26 4
gpt4 key购买 nike

我有一个 Swift 协议(protocol)定义如下:

protocol SmartContract {

func apply(transaction :Transaction)
func addBrokenRule(_ brokenRule: BrokenRule)
var brokenRules :[BrokenRule] { get set }
}

我在 SmartContract 上有一个扩展,定义如下:

extension SmartContract {

mutating func addBrokenRule(_ brokenRule :BrokenRule) {

if self.brokenRules == nil {
self.brokenRules = [BrokenRule]()
}

self.brokenRules.append(brokenRule)
}
}

我还有一个类 MoneyTransferContract,它符合协议(protocol)但未定义 brokenRules。这是因为我在扩展中定义了 brokenRules

class MoneyTransferContract : SmartContract { 

func apply(transaction :Transaction) { // do something here }
}

我的问题是如何确保 MoneyTransformContract 符合 SmartContract 协议(protocol)。无论如何,是否有 BrokenRule 可用于 MoneyTransformContract 而无需在不同的 SmartContracts 中一次又一次地定义它。

最佳答案

john doe 写道:

Is there anyway to have BrokenRule available to MoneyTransformContract without defining it again and again in different SmartContracts.

您想要的是该行为的父类(super class)/子类关系。

class SmartContract {
func apply(transaction :Transaction) {
//implemention
}
var brokenRules: [BrokenRule] = []
func addBrokenRule(_ brokenRule :BrokenRule) {
brokenRules.append(brokenRule)
}
}

class MoneyTransferContract : SmartContract {
// Gets `brokenRules` for free from superclass.
}

class BitCoinTransferContract : SmartContract {
// Gets `brokenRules` for free from superclass.
}

关于swift - 使用扩展在 Swift 中符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48087363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com