Lupurus
Lupurus

Reputation: 4189

Swift optional method in protocol without objc

I know, that making some methods in a Swift protocol requires to use @objc protocol. The problem is, that I can't use the objective c way, because I have a method in the protocol, which returns a Swift struct. So I'm getting the error, that I can't use the @objc protocol, because my method returns a result, which cannot be represented in objective c.

Unfortunately, I absolutely want to use an optional methods, because there are two methods, which are alternative and the user of my class shall choose, which way he want to use.

Upvotes: 3

Views: 1491

Answers (3)

bajocode
bajocode

Reputation: 360

Protocol Extensions

Swift 3

Another way to approach this problem without dealing with objective-C compatibility is to use optionals backed 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 optional by extending MyProtocol with a computed property:

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

And now you can create 'MyProtocol inheriting structs' that don't require the optionalProperty implementation.

Upvotes: 0

Well, I think I've a solution for you.

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

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

And then, you define as many protocols you need to express the various combinations of optional method(s) you need.

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

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

And last but not least, you'll define which protocols your class(es) implements.

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

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

Upvotes: 1

matt
matt

Reputation: 535202

What I do in this situation is return a class (compatible with Objective-C) which wraps the Swift struct. In other words, just make it so that everything Objective-C sees is compatible with Objective-C, and inside that you can do anything you like.

Upvotes: 2

Related Questions