Re: Best way to have KVC-compliant enum property in Swift 2?
Re: Best way to have KVC-compliant enum property in Swift 2?
- Subject: Re: Best way to have KVC-compliant enum property in Swift 2?
- From: Quincey Morris <email@hidden>
- Date: Wed, 29 Jul 2015 02:38:09 +0000
On Jul 28, 2015, at 18:07 , Rick Mann <email@hidden> wrote:
>
> dynamic var thumbnailURL : NSURL?
> dynamic var numFiles : NSNumber?
> dynamic var filesDownloaded : NSNumber?
> dynamic var downloadState : NSNumber? = DownloadState.notDownloaded.rawValue
I think you really should start from this:
> dynamic var thumbnailURL : NSURL?
> dynamic var numFiles : Int
> dynamic var filesDownloaded : Int
> dynamic var downloadState : Int = DownloadState.notDownloaded.rawValue
KVO already has the ability to transform properties with a simple numeric value into objects as necessary. You don’t need to reinvent this wheel.
However, the problem with the enum is not that it’s a scalar value, but that it’s not representable in Obj-C.
I suspect that downloadState will never need to be set via KVC**, or from Obj-C code, in which case there’s a slightly simpler solution than Charles’ suggestion. You can have 2 properties, one of which is an enum, and other is an immutable Int that’s observable, whose value is maintained via a simple didSet accessor on the enum property.
An alternative solution is to simply make downloadState an Int, not an enum (with class static Int vars for the allowable values). Yes, it’s less type-safe than an enum, but the KVO compatibility requirement may be paramount here. I’ve noticed that Swift tends to over-inspire us with tendencies towards over-generality and over-correctness. Sometimes the pragmatic solution is better.
** If it is, you can’t get the type safety of a Swift enum anyway, so I’d definitely use the Int-only solution of the last paragraph, given the relationship to KVC/KVO.
_______________________________________________
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