1

我有 2 种类型,A它们B实现相同的方法并具有相同的属性。我已经定义了一个扩展来获取每个A和的子属性中的值B。我想知道是否有办法将这 2 个扩展减少到 1 个方法。想象一下有更多的类型AB所以代码重复问题变得更糟。

更新:AB与许多其他类似的人一起生成。最初的计划是完全避免为Aor编写扩展B。我不知道这是否可能,但有人告诉我我可以为此使用 KeyPaths。属性名称必须不同。这是代码生成的副产品

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
    }
}
4

2 回答 2

2

我认为协议是解决您问题的方法。它们有助于使代码更通用。

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
    }
}
于 2018-09-21T15:20:11.203 回答
-1

据我了解,如果该方法与 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)) 

祝你好运。

于 2018-09-21T15:25:23.607 回答