[swift-evolution] Pitch: Expose enum properties backed by bridgeable types to Objective-C

Derrick Ho wh1pch81n at gmail.com
Thu Dec 15 00:16:49 CST 2016

You can currently access swift enums from objective c provided that it is
marked @objc and inherits from Int.

Objectivec can not however access a swift enum that inherits from a string.
I've asked the community about how they feel about enabling this but there
was little to no response.
On Thu, Dec 15, 2016 at 1:06 AM Charles Srstka via swift-evolution <
swift-evolution at swift.org> wrote:

> Many Cocoa classes which allow the user to choose from a list of items,
> such as NSPopUpButton, NSSegmentedControl, and NSTabView, offer the ability
> to bind the view to an integer or string in the model via KVO, through
> bindings such as “Selected Tag”, “Selected Index”, “Selected Identifier”,
> and the like. Since it can be tough to remember all the tags and whatnot
> that are associated with each view, it’s usually been helpful to create an
> enum to keep track of them… until now, since Objective-C cannot see Swift
> enums, and therefore they cannot be marked ‘dynamic’ for KVO.
> One can work around that by declaring two properties, one of which wraps
> the other, like this:
> enum SortMethod: Int {
>         case byName = 0
>         case bySize = 1
>         case byModificationDate = 2
> }
> var sortMethod: SortMethod {
>         willSet { self.willChangeValue(forKey: “sortMethod”) }
>         didSet { self.didChangeValue(forKey: “sortMethod”) }
> }
> @objc(sortMethod) private dynamic var objcSortMethod: Int {
>         get { return self.sortMethod.rawValue }
>         set(newValue) { self.sortMethod = SortMethod(rawValue: newValue)! }
> }
> However, this is cumbersome.
> I propose that if an property is typed to an enum, and that enum is backed
> by an Objective-C-bridgeable type, the property should be visible to
> Objective-C as its underlying type. So, for example, if you simply declared
> “var sortMethod: SortMethod” with the @objc attribute or the ‘dynamic’
> keyword, it would generate the longer code shown above. This would allow
> easy binding of UI elements in .xib files to enums in your model.
> We could introduce some sort of annotation allowing the user to specify a
> default case in the event that Objective-C tried to set the property to a
> value not covered in the enum, instead of just crashing. However, doing
> such a thing is almost always the result of a programmer error, so I do not
> consider this of high importance.
> Charles
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161215/37b18232/attachment.html>

More information about the swift-evolution mailing list