[proposal] Treat (case .Foo = bar) as a Boolean expression


(Thorsten Seitz) #1

I propose that (case .Foo = bar) should be treated as an expression with a Boolean value, so the result can be set to a variable or returned from a method.

I agree that this is an important use case that Swift doesn’t serve well right now, but I don’t think this is the right way to go.

Considering the following enumeration:

enum Bar {
case foo(name: String)
case notFoo
case unknownFoo
}

One of the things we’ve discussed in the past is that we could have enums automatically “synthesize” instance members for projecting cases as optional values or bools. For example, the above enum could be compiled into the equivalent of:

extension Bar {
func getAsFoo() -> String? { … }
var isNotFoo : Bool { … }
var isUnknownFoo : Bool { … }
}

Then you could just use:

if someBar.isUnknownFoo { … }
if someBar.isFoo != nil { … }
if let name = someBar. getAsFoo() {... }
someBar. getAsFoo()?.doThing()

I would strongly prefer pattern matching over magic methods, because of the following reasons:

(a) IMHO the latter are confusing because it is not clear and visible which methods have been created

(b) patterns allow IDE support for browsing usages of the various enums whereas browsing for a bunch of invisible automagically created methods is much more difficult and confusing
(c) I can't see a way of generating nice methods for accessing associated values (in various combinations) (see getAsFoo() example above and imagine a second or third parameter to Bar.foo)

-Thorsten

etc. There is a question of naming, and getting the details right, of course.

-Chris

···

Am 11. Mai 2016 um 05:31 schrieb Chris Lattner via swift-evolution <swift-evolution@swift.org>:

On May 10, 2016, at 4:33 AM, Sam Dods via swift-evolution <swift-evolution@swift.org> wrote:

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution