Compare Protocol in Swift vs Interface in Java

后端 未结 3 451
刺人心
刺人心 2021-01-29 19:42

I\'m going through the iOS tutorial from Apple developer page.

It seems to me that protocol and interface almost have the same functionality.

3条回答
  •  花落未央
    2021-01-29 20:19

    Essentially protocols are very similar to Java interfaces except for:

    • Swift protocols can also specify properties that must be implemented (i.e. fields)
    • Swift protocols need to deal with value/reference through the use of the mutating keyword (because protocols can be implemented by structures, enumerations or classes).
    • you can combine protocols at any point using "Protocol Composition". This replaces the older swift protocol way of protocol composition. For example, declaring a function parameter that must adhere to protocol Named and Aged as:
        func wishHappyBirthday(to celebrator: Named & Aged) {}
    

    These are the immediately apparent differences for a Java developer (or at least what I've spotted so far). There's more info here.

提交回复
热议问题