[swift-evolution] Ad hoc enums / options
Erica Sadun
erica at ericasadun.com
Tue Jun 7 15:29:51 CDT 2016
> On Jun 4, 2016, at 8:58 AM, Hooman Mehr <hooman at mac.com> wrote:
>
> How about this:
>
>
> Going back to Erica’s original example:
>
> func scaleAndCropImage(
> image: UIImage,
> toSize size: CGSize,
> operation: (.Fit | .Fill) = .Fit
> ) -> UIImage {
>
> And noting that we are already allowed to declare an enum inside the function, compiler can generate an enum scoped inside the function named the label of the enum:
>
> func scaleAndCropImage(
> image: UIImage,
> toSize size: CGSize,
> operation: (.Fit | .Fill) = .Fit
> ) -> UIImage {
> @_exposed num operation {
> case Fit
> case Fill
> }
>
> Then you could declare a var:
>
> var myOperation: scaleAndCropImage.operation = .Fill
>
> Then you can call:
>
> let scaledImage = scaleAndCropImage(image: myImage, toSize: theSize, operation: myOperation)
>
> @_exposed above would be a compiler private annotation for the auto generated enum that will make if visible outside of the function. This way the impact is minimal and such ad hoc enum would be just the same as any other enum. The only big change in the compiler would be the ability to make some declaration inside functions visible to the outside code.
This is my favorite approach (assuming it's technically feasible) as it preserves the limitation that the enumerations are scoped strictly to the function but can be referenced outside of it.
It allows type inference for dropped prefixes because the compiler can unambiguously match the ad hoc enumeration type to the parameter.
It introduces the possibility (for Matthew) of assigning a value to a variable.
It preserves the notion that an ad-hoc enum makes syntactic and semantic sense only with respect to its use in a function/method parameter list.
If an enumeration needs wider semantics, it should be a standalone type, whether as a nested or not.
Reiterating the reasons for this pitch:
It streamlines coding, eliminating standalone enumeration types that are used only once
It enables you to see all enumeration options at a glance, and can be reflected in the QuickHelp documentation
It encourages `switch` coding over `if-then-else` coding so each case is labeled and self documenting
It pushes semantics to the call-site in a way that simple Boolean flags cannot: `operation: .Fit` means more than `shouldFill: false`.
I'd like to know at this point whether Hooman's approach is even technically feasible, although it's horrible timing the Tuesday before WWDC to get core team feedback on anything.
-- Erica
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160607/df6f7def/attachment.html>
More information about the swift-evolution
mailing list