【问题标题】:In swift how do you define a type to a protocol with an internal type快速如何为具有内部类型的协议定义类型
【发布时间】:2015-10-20 18:25:19
【问题描述】:

我制定了以下协议。它定义了一个可以在startend 之间无限缩放的对象,给定一个值0-1

protocol Scalable {
    typealias ScalableType

    var start:ScalableType { get }
    var end:ScalableType { get }
    func scale(dub:Double) -> ScalableType?
    func series(count count:Int) -> [ScalableType?]
}

一个示例实现:

struct DoubleRange:Scalable {
    typealias ScalableType = Double
    let start:Double
    let end:Double

    var diff:Double {
        return end - start
    }

    func scale(dub: Double) -> Double? {
        return start + (dub * diff)
    }
}

我想做的是想办法将一个变量定义为一个属性,该属性允许任何Scalable,其中ScalableTypeUIColor

这行得通:

func foo<T where T:Scalable, T.ScalableType == UIColor>(scaler:T) {}

但我想不出一个等效的方法来定义这样的属性。正在考虑以某种方式制作包装器,但仍然无法弄清楚。

理想情况下,我想要这样表达的东西(即使显然不是编译代码)

var foo:Scalable<where Self.ScalableType == UIColor>?

【问题讨论】:

  • Scalable 属性的ScalableType 是否必须是UIColor 或者是任何ScalableScalableType 定义为UIColor 将有这个新属性?
  • @keithbhunter 对于这一次特定的实例,我想要一个对象符合Scalable 并且内部类型为UIColor 的属性。 Scalable 的其他实现将具有不同的内部类型。

标签: ios swift protocols swift2


【解决方案1】:

您可以将泛型放在类/结构定义中:

struct ObjectWithScalableColor<T: Scalable where T.ScalableType == UIColor> {
    let scalableColor: T
}

【讨论】:

  • 不幸的是,我不得不做var foo: ObjectWithScalableColor&lt;ColorImplementation&gt;,那时我还不如做var foo:ColorImplementaiton
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2019-11-23
  • 2016-11-09
相关资源
最近更新 更多