swift subclasses used in generics don't get called when inheriting from NSObject

前端 未结 3 1913
面向向阳花
面向向阳花 2021-01-14 20:44

Partial Solution Update at the end!

Attached is code that produces odd behavior. I copied it out of a swift playground so it should run in one fine.

3条回答
  •  有刺的猬
    2021-01-14 20:46

    This is a second way to avoid the problem.

    @matt originally suggested this but then deleted his answer. It is a good way to avoid the problem. His answer was simple. Mark the protocol with objc like this:

    // The Protocol
    @objc protocol P {
        init ()
        func doWork() -> String
    }
    

    This solves the above sample code and you now get the expected results. But doing this has side effects for swift. At least one of those is here:

    How to use @objc protocol with optional and extensions at the same time?

    For me, it began a chain of having to make all my protocols objc compatible. That made the change not worth it for my code base. I was also using extensions.

    I decided to stay with my original answer at least until Apple fixes this bug or there is a less invasive solution.

    I thought this one should be documented in case it helps someone else facing this problem.

提交回复
热议问题