3
votes

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.

3
What are the two methods? Can they be combined? Unfortunately I don't think this is possible in the current version of Swift. You may want to file a bug. - jtbandes
Maybe combining will be a way, I'll try, thank you! - Lupurus

3 Answers

2
votes

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.

1
votes

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.

0
votes

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.