[swift-users] if-case syntax ambiguity

Nicholas Outram nicholas.outram at icloud.com
Wed Nov 9 05:17:12 CST 2016


Hi

I’ve been drilling down on the syntax of enumerated types with associated data in the current release version of Swift 3.
I’ve pasted below a section of a Playground that captures an issue I’d like to raise.

In summary:

Consider the following 
enum Vehicle {
   case car(petrol: Bool, sizeCC: Int)
   case plane(engines : Int)
   case other(String)
   case none
}
let myJourney : Vehicle = .other("pogo stick")

Whereas the following is clear
if case .other(_) = myJourney

the following shorthand equivalent is potentially confusing for the sake of 3 characters
if case .other = myJourney

- In the first case, the presence of the underscore does communicate that something is being assigned, but dropped.
- In the second case, the reader could easily be mislead into thinking that = was supposed to be == as there no apparent place to assign anything.

My suggestion would simply be to drop the shorthand as it’s ambiguous?


Nick Outram




import Foundation

//: Consider the following enumerated type with associated data
enum Vehicle {
   case car(petrol: Bool, sizeCC: Int)
   case plane(engines : Int)
   case other(String)
   case none
}

//: Let's pick an example
let myJourney : Vehicle = .other("pogo stick")

//: I now want to test what case `myJourney` is.
//:
//: We cannot use the `==` operator because `Vehicle` has associated data. Instead we use `if case` and *simply drop the associated value* with `_` as shown above
if case .other(_) = myJourney {
   print("Somewhere nice?")
} else {
   print("Ok, it's a secret?")
}
//:The above is clear enough once you get used to the syntax. The `_` communicates that a value has been dropped.
//:
//: **However**, Swift 3 allows us to drop the parenthesis altogether and use the following shorthand:
if case .other = myJourney {
   print("Somewhere nice?")
} else {
   print("Ok, it's a secret?")
}
//: *Unlike the previous example, I do wonder if this is a language feature that needs review?*
//:
//: - On face value, reading this code as is there is an assignment operator `=` with nothing apparently being assigned.
//: - It also reads as if `=` should be `==`





-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161109/0b8ca6dc/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: EnumChangeSuggestion.playground.zip
Type: application/zip
Size: 11810 bytes
Desc: not available
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161109/0b8ca6dc/attachment.zip>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161109/0b8ca6dc/attachment-0001.html>


More information about the swift-users mailing list