Re: Mixing Swift and Objective-C protocols
Re: Mixing Swift and Objective-C protocols
- Subject: Re: Mixing Swift and Objective-C protocols
- From: Quincey Morris <email@hidden>
- Date: Wed, 07 Sep 2016 12:30:05 -0700
- Feedback-id: 167118m:167118agrif8a:167118sNDK6XnBCY:SMTPCORP
On Sep 7, 2016, at 02:43 , Gerriet M. Denkmann <email@hidden> wrote:
>
> But I cannot put it into my switch statement. The compiler says: Cannot assign value of type ‘ObjC!’ to type 'BitField?'
> How can I convince the compiler that the ObjC really implements the BitField protocol?
This isn’t how it works. You really should read the interoperability guide.
The immediate problem is that a pure Swift protocol isn’t the same as, nor is compatible with, an Obj-C protocol. They don’t even have the same names, because a pure Swift protocol name is mangled, while an Obj-C protocol name isn’t. They’re also namespaced differently, like Swift vs. Obj-C class names.
So you can get part of the way simply by forcing your Swift protocol to be Obj-C:
> @objc protocol BitField
> {
> init?(limit: UInt64, verbose: Int)
> }
Also, it’d be preferable to have a single definition, either on the Swift side or on the Obj-C side, and use interoperability via bridging headers to import the declaration to the other side. I’m not sure that duplicate definitions actually work, although they may, because Obj-C is more tolerant of that sort of thing.
The next problem you might run into is that your Swift classes (ClassA and ClassB) will need to be Obj-C classes (inherit from NSObject) in order to use an Obj-C protocol. That changes their behavior a bit, and you won’t be able to use pure Swift features that don’t interoperate with Obj-C, such as struct types or generics or non-trivial raw enums.
Writing Swift code using Obj-C classes is perfectly feasible, if you’re willing to stay in the world of Obj-C-compatible functionality. One alternative might be to create a pure Swift ClassC that conforms to the pure Swift protocol, but wraps an Obj-C instance that provides the functionality.
The other aspect is why you need to write any Obj-C code at all, since you can create Obj-C classes directly in Swift. The only obvious reason for sticking with Obj-C syntax would be if you’re re-using existing source and don’t want to have to translate it into Swift.
Sorry, I’m meandering a bit, but you have a lot of different options depending on what level of interoperability you want to dive into, and what kinds of restrictions you’re working with.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden