[英]Swift 4 KeyPath On Objects of Different Type
I have 2 types, A
and B
that implement the same methods and have the same properties on them.我有 2 种类型, A
和B
,它们实现相同的方法并具有相同的属性。 I have defined an extension to fetch a value in a sub property for each of A
and B
.我已经定义了一个扩展来为A
和B
每一个获取子属性中的值。 I want to know if there is a way to reduce those 2 extensions down to 1 method.我想知道是否有办法将这 2 个扩展减少到 1 个方法。 Imagine there are many more types like A
and B
so the code duplication problem becomes much worse.想象一下有更多的类型,比如A
和B
所以代码重复问题变得更糟。
Update: A
and B
are generated along with many others like them.更新: A
和B
与许多其他类似的东西一起生成。 The original plan is to avoid writing extensions at all for A
or B
.最初的计划是完全避免为A
或B
编写扩展。 I don't know if this is possible but I was told I could use KeyPaths for this.我不知道这是否可行,但有人告诉我可以为此使用 KeyPaths。 The properties names must be different.属性名称必须不同。 This is a byproduct of the code generation这是代码生成的副产品
struct A {
var something: Common
}
struct B {
var somethingElse: Common
}
struct Common {
var value1: String
var value2: String
}
extension A {
func valueFor(condition: Bool) -> String {
return condition ? self.something.value1 : self.something.value2
}
}
extension B {
func valueFor(condition: Bool) -> String {
return condition ? self.somethingElse.value1 : self.somethingElse.value2
}
}
I think protocols are the solution for your problem.我认为协议是您问题的解决方案。 They help to make code more generic.它们有助于使代码更通用。
protocol CommonContaining {
var common: Common { get set }
func valueFor(condition: Bool) -> String {
return condition ? self.common.value1 : self.common.value2
}
}
struct A {
var something: Common
}
struct B {
var somethingElse: Common
}
extension A: CommonContaining {
var common: Common {
return something
}
}
extension B: CommonContaining {
var common: Common {
return somethingElse
}
}
From what i have understand, if the method is related to Common struct then you should implement this method in the struct itself or to create extension to the struct :据我所知,如果该方法与 Common struct 相关,那么您应该在 struct 本身中实现此方法或创建对 struct 的扩展:
struct A
{
var something: Common
}
struct B
{
var somethingElse: Common
}
struct Common
{
var value1: String
var value2: String
func valueFor(condition: Bool) -> String {
return condition ? self.value1 : self.value2 }
}
var object_1 = A(something: Common(value1: "1", value2: "1"))
var object_2 = B(somethingElse: Common(value1: "1", value2: "2"))
print(object_1.something.valueFor(condition: true))
print(object_2.somethingElse.valueFor(condition: false))
Good luck.祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.