Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

swift - Extend existing protocols to implement another protocol with default implements

Is it possible to add protocol compliance to a different protocol by way of an extension?

For instance we would like A to comply with B:

protocol A {
  var a : UIView {get}
}

protocol B {
  var b : UIView {get}
}

I want to give a default implementation (compliance) of B to objects of type A

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

The motivation being to reuse objects of A in cases where a B is required without creating my own "bridge"

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 ...

  }
}

As a side note we can extend a class to implement a protocol

class C {
  let C : UIView
}

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

and protocols can give default implementations

extension A {
  // a default implementation
  var a : UIView {
     return UIView()
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When extending A, you could specify that the type also conforms to B:

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

Then make your type conform to A and B, e.g.

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

Due to the protocol extension, instances of MyStruct will be able to use a and b, even though only a was implemented in MyStruct:

let obj = MyStruct()
obj.a
obj.b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...