In a functional language, if and switch statements should return values.

Originator:warrenforeign
Number:rdar://17218977 Date Originated:6/7/14
Status:Open Resolved:
Product:Swift Product Version:Xcode 6 build 6A215l
Classification:Enhancement Reproducible:yes
 
Summary:
In a functional language, if and switch statements should return values. I know there is the ternary operator (? :) but there are cases where it would make sense to have slightly larger conditionals without having to make an actual function. These cases would be much more readable if they could be written as if/else or switch statements (would be quite ugly using nested ternaries).

See for example the following example from http://learnyouahaskell.com/starting-out

doubleSmallNumber x = if x > 100  
                        then x  
                        else x*2

Steps to Reproduce:
1. Open a playground
2. Try to refactor the first switch example to pull the let to the top level as follows
let vegetable = "red pepper"
let vegetableComment = switch vegetable {
    case "celery" :
        "Add some raisins and make ants on a log."
    case "cucumber", "watercress":
        "That would make a good tea sandwich."
    case let x where x.hasSuffix("pepper"):
        "Is it a spicy \(x)?"
    default:
        "Everything tastes good in soup."
    }
3. Note that it does not work.

Expected Results:
The value of vegetableComment is "Is it a spicy red pepper?"

Actual Results:
The first time I tried this I got no error in the playground, yet it failed to give vegetableComment a value.  I tried again and did get an error message the second time. (Expected initial value after '='.)

Version:
Version 6.0 (6A215l)

Notes:
Functional programming FTW! Everything that can reasonable be an expression with a value should be!

Comments

Following works, but sure language should support feature you mentioned!

let vegetable = "red pepper" let vegetableComment = { switch vegetable { case "celery" : return "Add some raisins and make ants on a log." case "cucumber", "watercress": return "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): return "Is it a spicy (x)?" default: return "Everything tastes good in soup." } }()


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!