Home > Software engineering >  How is the ampersand in the return signature in Swift used?
How is the ampersand in the return signature in Swift used?

Time:09-12

I came across the following code:

  func makeContentView() -> UIView & UIContentView {
     return DatePickerContentView(self)
  }

How does the return type of UIView & UIContentView work? This is the first time I came across this. Does this mean we can do multiple &?

I tried to search but I am not familiar with the corresponding technical term.

CodePudding user response:

It's just a way of describing a type. For the notation, read the Protocol Composition section of https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID282.

UIView is not a protocol but it does involve inheritance: it's a class. Accordingly, you can compose a maximum of one class with your list of composed protocols. As the doc says:

In addition to its list of protocols, a protocol composition can also contain one class type, which you can use to specify a required superclass.

So this code means the return type here is "a type that inherits from the UIView class and that also adopts the UIContentView protocol."

And yes, you can do composition on multiple protocols. In our code base we often compose ten or twenty protocols in this way.

  • Related