I've got a class with a subscript property (it inherits from another class that takes type 'AnyObject' in a subscript).
public var payFrequency: PayFrequency {
get { return self["payFrequency"] as? PayFrequency ?? .Weekly }
set(value) { self["payFrequency"] = value }
}
The compiler complains that I:
Cannot assign value of type 'PayFrequency' to type AnyObject
When I try to cast value
to AnyObject
:
set(value) { self["payFrequency"] = value as? AnyObject }
...it compiles, but fails to set the value to anything (when I get the variable, it always returns the default .Weekly
).
Here's the enum:
public enum PayFrequency: String {
case Weekly = "weekly"
case SemiMonthly = "semi-monthly"
case BiWeekly = "bi-weekly"
case Monthly = "monthly"
}
How can I get this enum to work with AnyObject, OR how can I update the getter/setter of the subscript to properly store the enum value?
AnyObject
is not compatible with enums, as enums are value types, while AnyObject
corresponds to a reference.
You can try using NSString
for the enum declaration, and use it's raw value within the property.
public enum PayFrequency: NSString {
public var payFrequency: PayFrequency {
get { return PayFrequency(rawValue: self["payFrequency"] as? String ?? "") ?? .Weekly }
set(value) { self["payFrequency"] = value.rawValue }
}
or keep the enum declaration the same, Swift should be able to bridge between String
and NSString
.