Search code examples
iosswiftclassprotocolscomposition

What is difference between '&' and ',' in swift about Protocol Composition


I have a question

In swift,

class Card : Equatable & CustomStringConvertible

and

class Card : Equatable, CustomStringConvertible

I think there are doing the same things. What is different??


Solution

  • From the Swift documentation on protocols, I think & is mainly used when you are requiring a variable to adopt to multiple protocols, ex:

    func wishHappyBirthday(to celebrator: Named & Aged) {
        print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
    }
    

    And you use , when you want to adopt a custom struct/class to multiple protocols:

    struct SomeStructure: FirstProtocol, AnotherProtocol {
        // structure definition goes here
    }