Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a protocol method in swift optional?

How can I make a protocol method in swift optional? Now all the methods in a protocol is seems to be required. Is there any other work arounds?

like image 667
Riaz Avatar asked Feb 19 '26 17:02

Riaz


1 Answers

While you can use @objc in Swift 2 you can add a default implementation and you don't have to provide the method yourself:

protocol Creatable {
    func create()
}

extension Creatable {
    // by default a method that does nothing
    func create() {}
}

struct Creator: Creatable {}

// you get the method by default
Creator().create()

However in Swift 1.x you could add a variable which holds an optional closure

protocol Creatable {
    var create: (()->())? { get }
}

struct Creator: Creatable {
    // no implementation
    var create: (()->())? = nil

    var create: (()->())? = { ... }

    // "let" behavior like normal functions with a computed property
    var create: (()->())? {
        return { ... }
    } 
}

// you have to use optional chaining now
Creator().create?()
like image 198
Qbyte Avatar answered Feb 21 '26 13:02

Qbyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!