UIView in Swift<FooProtocol, BarProtocol> Can you make a considerable declaration?

Question: Question:

In Objective-C, you can declare variables and define properties with specific types that implement multiple protocols as shown below.

UIView<FooProtocol, BarProtocol>* myView = ...

Is there a similar way to write in Swift?

Answer: Answer:

You can't do the same thing directly with Objective-C, but I think you can do the same with type extensions. If the type T conforms to the protocol, it is in a global state, so this is fine.

protocol FooProtocol {
    var foo: String { get }
}
protocol BarProtocol {
    var bar: String { get }
}

extension UIView: FooProtocol, BarProtocol {
    var foo: String { return "foo" }
    var bar: String { return "bar" }
}

let a = UIView()
a.foo // "foo"
a.bar // "bar"
Scroll to Top