1

Encountered below error when trying to use Unmanaged Objects with swift Protocol

'Unmanaged' requires that 'MyProtocol' be a class type

protocol MyProtocol:class {}
class MyController: MyProtocol {}
func test() {
    let listController : MyProtocol = MyController()
    let p = Unmanaged<MyProtocol>.fromOpaque(listController).takeUnretainedVlue()
//          ^^^^^^^^^
}
Alexander Ushakov
  • 5,139
  • 3
  • 27
  • 50
Peter Tang
  • 51
  • 4

1 Answers1

0

Update:

If you can ensure that protocol always be some class object than you can use explicit type conversation:

// get unsafe pointer to delegate object
let delegate : MyProtocol = some_object
let my_unsafe_pointer = Unmanaged.passUnretained( delegate as AnyObject ).toOpaque()

// get delegate back from unsafe pointer
let delegate = Unmanaged<AnyObject>.fromOpaque( my_unsafe_pointer ).takeUnretainedValue() as! MyProtocol

Previous answer

Protocol variable is not a regular object as Unmanaged requires. Protocol just stores something that conforms to it. You can't get object or structure that is wrapped in protocol. So you must use original object with Unmanaged instead of protocol. If protocol is a parameter of function consider using generics: see https://stackoverflow.com/a/51487124/4915707

Alternatively, you can add @objc before protocol definition to make it compatible with Objective-C. Then your protocol will work like an object.

Alexander Ushakov
  • 5,139
  • 3
  • 27
  • 50