Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Enums as parameters in Swift Protocols optional functions

I have this enum in Swift

enum Direction: Int{
  case Left2Right = 0, Right2Left
}

And this protocol

@objc protocol CellDelegate : NSObjectProtocol{
   optional func has(direction:SwipeDirection) -> Bool
}

I am getting this error Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C

Can anybody tell me why do i get this error and how to fix it please? Thanks!

like image 943
Dănuț Mihai Florian Avatar asked Feb 18 '15 17:02

Dănuț Mihai Florian


People also ask

Can enum conform to Swift protocol?

Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.

Can enum have functions in Swift?

Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.

How can an optional method be defined in Swift protocols?

Swift protocols on their side do not allow optional methods. But if you are making an app for macOS, iOS, tvOS or watchOS you can add the @objc keyword at the beginning of the implementation of your protocol and add @objc follow by optional keyword before each methods you want to be optional.

How do you make a function optional in Swift?

To define Optional Protocol in swift you should use @objc keyword before Protocol declaration and attribute / method declaration inside that protocol.


1 Answers

The @objc attribute makes the protocol compatible (i.e. usable) with Objective C. But swift enums (prior to 1.2 beta) are not available in Objective C. So you cannot use a swift enum in that protocol.

I think that the best solution is to use swift 1.2 - it's still in beta (as of today), but it's possible to apply the @objc attribute to swift enums.

like image 184
Antonio Avatar answered Sep 19 '22 01:09

Antonio