otusweb
otusweb

Reputation: 1678

Swift protocol to return a dictionary of selector

I'm trying to create a protocol where one of the methods will return a dictionary of selector. But I'm running into an issue...

here is the protocol code:

@objc public protocol MazeProtocol: AnyObject {
    @objc static func configurations() -> [String:Selector]
}

and here is the compiler error I'm getting: MazeTableViewController.swift:12:24: Method cannot be marked @objc because its result type cannot be represented in Objective-C

If I remove the @objc in front of the method, I get a similar error.

Upvotes: 1

Views: 312

Answers (3)

Rob Napier
Rob Napier

Reputation: 299275

As RX9 suggests, there's no reason (at least that you've explained) to mark this as @objc, at either the function or protocol level. The following is fine:

public protocol MazeProtocol: AnyObject {
    static func configurations() -> [String:Selector]
}

The point of @objc is to allow ObjC objects to interact with this protocol. If you have Objective-C that needs to interact with this protocol, I strongly suggest defining this protocol on the ObjC side rather than on the Swift side. (But if you have that case, leave a comment, and we can walk through how to get what you need; as olejnjak notes, you can't put Selector directly in a dictionary that ObjC understands.

Upvotes: 0

Natarajan
Natarajan

Reputation: 3271

As you can't use Selector in Objective C Dictionary directly, you can change your Swift dictionary's both key and value type to String as like below.

@objc public protocol MazeProtocol: AnyObject {
    @objc static func configurations() -> [String:String]
}

So when you want to get your Selector from configurations dictionary, get it as like below.

let selectorString = configurations()["KeyToSelector"]
let selector = NSSelectorFromString(selectorString)

Upvotes: 0

olejnjak
olejnjak

Reputation: 1363

Well [String: Selector] is Dictionary<String, Selector> which is a struct and structs cannot be represented in Objective-C, so you would need an NSDictionary

@objc public protocol MazeProtocol: AnyObject {
    @objc static func configurations() -> NSDictionary
}

Upvotes: 3

Related Questions