【问题标题】:Is there any non written rule that an associatedtype shouldn't be constrained by a concrete type?是否有任何非书面规则规定关联类型不应受具体类型的约束?
【发布时间】:2018-12-04 17:24:09
【问题描述】:
class Human {
    var name : String?
}

class Man : Human {
    var numberOfWallets : Int?
}

class Woman : Human {
    var numberOfPurses : Int?
}

protocol P {
    associatedtype Person : Human
    func printX(of person : Person)
    func printY(of person: Person)
}

这允许Human 成为它的typealias

class C : P {
    typealias Person = Human
    func printX(of person: Human) {
        print(person.numberOfCars)
    }

    func printY(of person: Human) {
        print(person.name)
    }
}

如您所见,Person 类型受Human 约束,Human 本身就是一个具体类型。我想知道这是否普遍。我的直觉告诉我,这实际上表明我不应该使用协议,而类本身就很好。

或者我应该这样做

protocol P {
    associatedtype Person
    func printX(of person : Person)
    func printY(of person: Person)
}

class C : P {
    func printX(of person: Man) {
        print(person.numberOfCars)
    }

    func printY(of person: Man) {
        print(person.name)
    }
}

这不允许WomanMan 实例同时用于C 实例。

我知道这取决于我想做什么。但我的问题真的是:用具体类型约束关联类型有意义吗?!

或相关类型只是不受协议约束或受协议约束,而不是具体类型...

【问题讨论】:

  • 它们可能不像协议约束的关联类型那样常见,但类约束的关联类型肯定有有效的用例,就像类约束的泛型占位符有有效的用例一样。
  • 所以回答我自己的问题:这样做很好。我认为这可能不好的原因是因为我是使用 PAT 的新手,而且大多数 Swift 文档都被限制在另一个协议中。即我没有遇到受具体类型约束的关联类型......

标签: swift protocols swift-protocols design-principles associated-types


【解决方案1】:

在这一行

 associatedtype Person : Human

约束不是具体的。它以并行方式适用于两种继承。

• 如果 Human 是协议,则 Person 必须是采用它的具体类型。

• 如果 Human 是一个类,则 Person 必须是从它派生的具体类型。

两者都是有用且合法的,并且彼此非常相似。

【讨论】:

  • 您正在解释: 的作用。继承或收养。我的问题:让您的关联类型基于具体类型是否很常见?您是否在 Swift/Apple 代码中看到了用具体类型对其进行约束的实例?因为我没见过……
  • Swift 标准库都是结构(和协议),所以很明显你不会看到类约束。
  • 一个结构约束的例子也足以使我的主张无效。我的意思是 struct 不也是一个具体的类型吗?
  • 不,这没有任何意义,也不合法。正如我在回答中所说,带有冒号的约束是关于继承的。类和协议分别通过继承和采用进行继承。结构没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 1970-01-01
相关资源
最近更新 更多