24

是否可以通过扩展将协议合规性添加到不同的协议?

例如,我们希望 A 遵守 B:

protocol A {
  var a : UIView {get}
}

protocol B {
  var b : UIView {get}
}

我想为 A 类型的对象提供 B 的默认实现(合规性)

// This isn't possible
extension A : B {
  var b : UIView {
    return self.a
  }
}

动机是在不需要创建我自己的“桥梁”的情况下重用 A 的对象

class MyClass {
  func myFunc(object : A) {
    ...
    ...
    let view = object.a 
    ... do something with view ...

    myFunc(object)      // would like to use an 'A' without creating a 'B'
  }

  func myFunc2(object : B) {
    ...
    ...
    let view = object.b
    ... do something with view ...

  }
}

作为旁注,我们可以扩展一个类来实现协议

class C {
  let C : UIView
}

// this will work
extension C : B {
  var B : UIView {
    return self.c
  }
}

和协议可以给出默认实现

extension A {
  // a default implementation
  var a : UIView {
     return UIView()
  }
}
4

2 回答 2

20

扩展时A,您可以指定该类型也符合B

extension A where Self: B {
    var b : UIView {
        return self.a
    }
}

然后使您的类型符合Aand B,例如

struct MyStruct : A, B {
    var a : UIView {
        return UIView()
    }
}

由于协议扩展,实例MyStruct将能够使用aand b,即使仅a在 中实现MyStruct

let obj = MyStruct()
obj.a
obj.b
于 2016-05-20T18:04:58.230 回答
5

您可以从以下A 位置继承B

protocol A: B { var a: String { get } }
protocol B    { var b: String { get } }

// Default implementation of property b
extension A {
    var b: String { get { return "PropertyB" } }
}


class MyClass: A {
    var a: String { get { return "PropertyA" } }

    func printA(obj: A) {
        print(obj.a)
        printB(obj)
    }

    func printB(obj: B) {
        print(obj.b)
    }
}

let obj = MyClass()
obj.printA(obj)

由于A继承自B,因此 中的每个属性B都可以在 中使用A

于 2016-05-19T15:42:02.673 回答