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

Eduardo Mourey Lopez Ne edmourey at icloud.com
Tue May 10 22:46:53 CDT 2016


Hi Chris

I do agree that it is incosistent that case works in an if but you can’t assign it to a bool

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

var xx = Bar.foo(name: "Hello")

if case Bar.foo(let name) = xx where name == "Hello” {   //This work ok
    print("Hola")
}
var bool = case Bar.foo(let name) = xx where name == “Hello”  //But this doesn’t ???

//The other problem that I see is that the var “xx” seems to get lost int case by having it in the middle
//I think it will be better to have an alternative keyword for a single case, like ‘match’ that allows the variable
//to be at the begging 

//This looks much better 
var bool = xx match Bar.foo(let name) where name == “Hello”


Thanks
> On May 10, 2016, at 10:31 PM, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On May 10, 2016, at 4:33 AM, Sam Dods via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> 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() 
> 
> etc.  There is a question of naming, and getting the details right, of course.
> 
> -Chris
> _______________________________________________
> 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/20160510/4e0128a1/attachment.html>


More information about the swift-evolution mailing list