gpt4 book ai didi

ios - Swift:如何实现协议(protocol)(接口(interface))的部分类实现?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:12:26 26 4
gpt4 key购买 nike

来自 Java/C++ 等语言,我们习惯于部分或抽象类实现,例如

protocol ProtocolA {
func x()
func y()
}

// attempt to partially implement ProtocolA
class AbstractProtocolA: ProtocolA {
func x() { /* implementation */ }

// does not implement function y
}

class ConcreteA1: AbstractProtocolA {
func y() { /* implementation */ }
}

class ConcreteA2: AbstractProtocolA {
override func x() { /* implementation */ }
func y() { /* implementation */ }
}

但这在 Swift 中是不可能的,在这种情况下我会得到编译错误OOD用例?

更新:规避此限制的一种方法是:

enum ProtocolAError: ErrorType {
case NotImplementedException(methodName: String)
}

class AbstractProtocolA: ProtocolA {
func x() { /* implementation */ }

func y() { throw ProtocolAError.NotImplementedException(methodName: "y") }
}

但在这里我们将设计/编程错误(即实例化抽象 AbstractProtocolA)转移到运行时而不是编译时。

最佳答案

您可以使用协议(protocol)扩展创建协议(protocol)的默认实现:

protocol ProtocolA {
func x()
func y()
}

extension ProtocolA {
func x() {
// Do something (or nothing) here as a default implementation
}
}

希望它有用;)

PS:看看 protocol oriented programming in swift,这里有一些链接: https://www.raywenderlich.com/109156/introducing-protocol-oriented-programming-in-swift-2 https://developer.apple.com/videos/play/wwdc2015/408/

关于ios - Swift:如何实现协议(protocol)(接口(interface))的部分类实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519973/

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