Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define property that must be a subclass AND conform to protocol

Tags:

swift

swift2

In Swift 2.0, how can I do the equivalent of @property (nonatomic, strong) NSManagedObject*<SomeProtocol> model?

Basically, I’m trying to define a property on my class that must both be a subclass of NSManagedObject AND conform to SomeProtocol (I will be calling methods defined by both).

I saw this: https://stackoverflow.com/a/25826948/363789, but I'm not sure how I can apply this syntax to property definition...

like image 857
elsurudo Avatar asked Sep 07 '15 14:09

elsurudo


People also ask

Can we define property in protocol?

A protocol can have properties as well as methods that a class, enum or struct conforming to this protocol can implement. A protocol declaration only specifies the required property name and type. It doesn't say anything about whether the property should be a stored one or a computed one.

What are the properties protocols?

It aims to ensure that neighbours exchange sufficient information in a timely manner to minimise the scope for disputes between them; and to enable any such disputes to be readily resolved, including by alternative disputes resolution (ADR), keeping costs to a minimum.

CAN protocols have properties?

A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn't specify whether the property should be a stored property or a computed property—it only specifies the required property name and type.

What's the difference between a protocol and a class in Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.


1 Answers

Swift 4

This is now possible in Swift 4 using the following syntax:

var myObject: NSManagedObject & SomeProtocol
like image 97
Marián Černý Avatar answered Sep 20 '22 23:09

Marián Černý