Class-Only Protocols in Swift

后端 未结 4 1336
攒了一身酷
攒了一身酷 2021-02-03 20:51

I want some of my classes (not all) to conform using \'Class-Only Protocols\' from docs. What I am doing is

protocol RefreshData: class, ClassA, ClassB
{
    fun         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-03 21:39

    The answers provided by Chris and Wain are correct. I'm just adding a few more details here.

    Defining a protocol

    You must distinguish the concept of declaring a protocol (available for classes)

    protocol RefreshData: class {
        func updateController()
    }
    

    Defining a class

    ...from the concept of conforming your class to a protocol

    class ClassA: RefreshData {
        func updateController() {
    
        }
    }
    

    Conforming a class you don't own

    Sometimes you want to conform a class to a protocol but you don't own the source code for that class. In this case you can use an extension

    extension ClassB: RefreshData {
        func updateController() {
    
        }
    }
    

提交回复
热议问题