Search code examples
swiftstaticprotocols

when should I use protocol to replace static function


I'm confused by when to use protocol/static function.

class A {
    func a() {
        B.b()
    }
}

class B {
    static func b() {
        print("do sth.")
    }
}

class A: B {
    func a() {
        self.b()
    }
}

protocol B {
    func b()
}

extension B {
    func b() {
        print("do sth.")
    }
}

One use protocol and one use static function. Which one is better?

EDIT: For more detail, the func b() will show an alert. A is a Controller, which will send a request. If it failed, the alert should be shown. Please note there are many controllers need to show the same alert so I use b() to show them.


Solution

  • One use protocol and one use static function. Which one is better?

    They're different things entirely, so use the one that does the thing you need:

    protocol: A protocol specifies one or more functions that will be implemented by any class that adopts that protocol. Your class A adopts protocol B, so you can pass an instance of A to any method that requires an object that conforms to B. There might be classes C, D, and E that also adopt protocol B, and if so you could also pass instances of any of those classes to that same method.

    static function: A static function is similar to a class method in Objective-C, which is to say that you can call the function without needing an instance of the class it belongs to. When you say B.b() in your first example, you're doing exactly that -- calling b() without having an instance of B.

    The examples you've given are so simple that it's not clear what you're trying to do, so it's hard to say one is better than the other. In actual use, though, it's unlikely that you'd mix them up. Consider UITableViewDataSource, for example: it's a protocol that specifies the interface that an object acting as a data source for a table has to conform to. It doesn't make much sense to try to do that with static functions – the whole point is that the table doesn't know what the implementation of functions like numberOfSections(in:) should be, but it does need to know what function to call in the data source object.