Re: swift - making array of subclass of class also conforming to protocol
Re: swift - making array of subclass of class also conforming to protocol
- Subject: Re: swift - making array of subclass of class also conforming to protocol
- From: Quincey Morris <email@hidden>
- Date: Sat, 28 Nov 2015 10:32:05 -0800
- Feedback-id: 167118m:167118agrif8a:167118s_JevKZhdU:SMTPCORP
On Nov 28, 2015, at 03:51 , Roland King <email@hidden> wrote:
>
> private var myViews : Array<UIView,MasterControllable> // nope
> private var myViews : Array<T:UIView where T:MasterControllable> // nope
The problem is that you’re defining a variable. It can’t be generic — that would imply a different variable for each specialization. It can’t be UIView+MasterControllable (in some syntax), because no such *single* type exists. You could do something like this (which compiles in a playground):
> protocol MasterControllable
> {
> func implementMe ()
> var view: UIView { get }
> }
>
> extension MasterControllable
> {
> var view: UIView { return self as! UIView }
> }
>
> public class MyView1 : UIView, MasterControllable
> {
> func implementMe () {}
> }
>
> public class MyView2 : UIView, MasterControllable
> {
> func implementMe () {}
> }
>
> private var myViews : [MasterControllable] = [MyView1 (frame: .zero), MyView2 (frame: .zero)]
That means you’d use 'myViews [i]’ to get to the MasterControllable methods and ‘myViews [i].view’ to get to the view methods.
What you’re trying to do sounds reasonable, though. If there was syntax like ‘class <SomeClass, SomeProtocol>’ to go along with ‘protocol <SomeProtocol, OtherProtocol>’, then you could declare an 'Array<class <UIView, MasterControllable>>’. However, I don’t know exactly what kind of type this would be — not exactly a class *or* a protocol.
Declaring a parent class that’s a UIView subclass and implements the protocol as placeholder methods isn’t a stupid idea. (Or, better still, implements them as defaults in a protocol extension.) It’s just grunt work like we’ve been doing for years.
You should ask this question in the Swift developer forum area. There are smarter people there who love solving this kind of thing.
_______________________________________________
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