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: Charles Srstka <email@hidden>
- Date: Tue, 28 Jul 2015 20:57:26 -0500
> On Jul 28, 2015, at 8:07 PM, Rick Mann <email@hidden> wrote:
>
> I'd like to have a Swift enum that lays out a set of states, and a property of that type on an object that is KVObservable (i.e. dynamic). I don't think this is possible. What I settled on was this:
>
> class
> Model : MPObject
> {
> enum
> DownloadState : NSNumber
> {
> case notDownloaded = 0
> case downloadStarted = 1
> case downloadComplete = 2
> case downloadError = 3
> }
>
> dynamic var thumbnailURL : NSURL?
> dynamic var numFiles : NSNumber?
> dynamic var filesDownloaded : NSNumber?
> dynamic var downloadState : NSNumber? = DownloadState.notDownloaded.rawValue
> }
>
> But that's kinda gross. Any better approaches? Thanks!
It’s a lot of boilerplate, but you could do something like this:
(disclaimer: written in Mail)
class Model: MPObject {
enum DownloadState : Int {
… cases ...
}
var downloadState: DownloadState = .notDownloaded {
willSet {
self.willChangeValueForKey("downloadState")
}
didSet {
self.didChangeValueForKey("downloadState")
}
}
func valueForKey(key: String) -> AnyObject? {
if key == "downloadState" {
return NSNumber(integer: self.downloadState.rawValue)
} else {
return super.valueForKey(key)
}
}
func setValue(value: AnyObject?, forKey key: String) {
if key == "downloadState" {
guard let rawValue = value as? Int, state = DownloadState(rawValue: rawValue) else {
… handle this condition somehow …
}
self.downloadState = state
} else {
super.setValue(value, forKey: key)
}
}
}
I think this should allow a native Swift enum to be KVC-compliant.
Alternative way to do it, with a little less boilerplate but an extra property:
class Model: MPObject {
enum DownloadState : Int {
… cases ...
}
var downloadState: DownloadState = .notDownloaded {
willSet {
self.willChangeValueForKey("kvcDownloadState")
}
didSet {
self.didChangeValueForKey("kvcDownloadState")
}
}
dynamic var kvcDownloadState: Int {
get {
return self.downloadState.rawValue
}
set(rawValue) {
guard let state = DownloadState(rawValue:rawValue) else {
… handle this condition somehow ...
}
self.downloadState = state
}
}
}
Charles
_______________________________________________
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