Making a typealias with a protocol

Viewed 1144

Can I define 2 typealias like this?

typealias MyViewControllerTypeOne = UIViewController

typealias MyViewControllerTypeTwo = UIViewController, MyGreatProtocol

I already know that the second one does not work with this syntax.

But what is the way to get the result I want? (I presume what I want is pretty obvious here.)

2 Answers

In Swift 4 you can now compose a class with any number of protocols by using the & operator:

typealias MyViewControllerTypeTwo = UIViewController & MyGreatProtocol

Check the WWDC 2017 "What's New in Swift" around 05:23.

You can also see the section "Protocol Composition" in the Swift 4.0 documentation, although it doesn't mention composing classes with protocols.

You can do it as a tuple -

typealias tupleAlias = (viewController :UIViewController,protocol: MyGreatProtocol)

EDIT: example use-

typealias PersonTuple = (name: String, address: String)

    override func viewDidLoad() {
        super.viewDidLoad()
        let tupleInstance = getPerson(for: "Jack")
        print(tupleInstance.address)//Prints India
    }
    func getPerson(for name: String) -> PersonTuple {
        return (name, "India")
    }
Related