【问题标题】:Swift different default implementations for protocol propertySwift 协议属性的不同默认实现
【发布时间】:2020-07-24 13:37:50
【问题描述】:

我知道你可以给一个像这样的协议扩展的默认值

protocol SomeProtocol {
    var prop: String { get }
}

extension SomeProtocol {
    var prop: String {
        return "defaultValue"
    }
}

struct SomeA: SomeProtocol {}
struct SomeB: SomeProtocol {}

let a = SomeA()
let b = SomeB()

debugPrint(a.prop) // prints defaultValue
debugPrint(b.prop) // prints defaultValue

但是有没有办法为这样的协议的不同实现设置不同的默认值,而不为符合此协议的每个类或结构实现属性?

debugPrint(a.prop) // prints defaultValue
debugPrint(b.prop) // prints differentDefaultValue

或一些类似的模式来做这样的事情?

【问题讨论】:

  • 你试过什么?什么不起作用?
  • 您的答案有效,但我需要为许多类或结构使用相同的实现,我不想一次又一次地编写相同的实现。

标签: ios swift protocols swift-protocols protocol-oriented


【解决方案1】:

协议继承。

protocol ?: SomeProtocol { }

extension ? {
  var prop: String { "?" }
}

struct SomeA: SomeProtocol { }
struct SomeB: ? { }
struct SomeC: ? { }

SomeA().prop // "defaultValue"
SomeB().prop // "?"
SomeC().prop // "?"

【讨论】:

  • 谢谢,但我知道这是可以做到的。当我指的是默认值时,我的意思是 SomeB、SomeC、SomeD 获取默认值而不实现它。不过我会编辑问题。
  • 目前还不清楚您要解决什么问题,但我已对其进行了编辑。
  • 不错!非常感谢。这正是我想要的。
  • 我实际上是在尝试根据不同的类为 LoggerProtocol 获取不同的打印描述。所以现在我有一个 BaseLoggerProtocol 和其他人从这个 description 属性继承。
猜你喜欢
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 2022-01-02
  • 2021-04-30
相关资源
最近更新 更多