Fast optional method in protocol without objc

I know that creating some methods in the Swift protocol requires using @objc protocol

. The problem is that I cannot use the objective way c because I have a method in the protocol that returns a Swift structure. So I get the error that I cannot use the @objc protocol because my method is returning a result that cannot be represented in object c.

Unfortunately, I absolutely want to use optional methods because there are two methods that are alternatives and the user of my class has to choose which way they want to use.

+3


source to share


3 answers


In this situation, I am returning a class (Objective-C compatible) that wraps the Swift framework. In other words, just make it so that whatever Objective-C sees is Objective-C compatible, and internally that you can do whatever you like.



+2


source


Well I think I have a solution for you.

First it is the protocol with the required method (s).

protocol A {
  func A() -> ()
}

      

And then you define so many protocols that you need to express different combinations of the optional method (s) you want.



protocol APrimo {
  func B() -> ()
}

protocol ASecundo {
  func C() -> ()
}

      

Last but not least, you will determine which protocols your classes implement.

class AClass: A, ASecundo {
  func A() -> () { }
  func C() -> () { }
}

      

Side note: you can of course define additional protocols as inheriting from the required protocol. I find the style I used here better, but that's just me.

0


source


Protocol extensions

Swift 3

Another way to solve this problem without using objective-C interoperability is to use the options supported by protocol extensions.

Define your optional property or method:

protocol MyProtocol {
    var optionalProperty: Int? { get }
    var requiredProperty: Int { get }
}

      

Implement the default behavior of your option by extending MyProtocol

with a computed property:

extension MyProtocol {
    var optionalProperty: Int? { return nil }
}

      

And now you can create ' MyProtocol

inheritance structures' that don't require implementation optionalProperty

.

0


source







All Articles