Would C# style Expression-bodied members be considered Swifty?


(Francois Green) #1

I'm trying to get my head around the philosophy of Swift in the area of what is considered too terse. Looking at this feature in C#, which is also making its way to Java, I'm wondering if it would be out of step with Swift's principles?

func joiner(first: String, second: String) -> String {
    return first + second
}

func stitch(first: String, second: String) => joiner
//vs
func stitch(first: String, second: String) -> String {
    return joiner(first: first, second: second)
}

struct Color {
    let name: String 
    let hex: String
    let rgb: [Int, Int, Int]
}

func splash(name: String, hex: String, rgb: [Int, Int, Int]) => Color 
//vs
func splash(name: String, hex: String, rgb: [Int, Int, Int]) -> Color {
    return Color(name: name, hex: hex, rgb: rgb)
}

I see its appeal, but I mostly write Java and would seize any opportunity to type less code :wink:


(Joe Groff) #2

Swift already allows "expression bodied" closures, where if you write something like map { $0 + 1 } the expression is implicitly returned. It would seem consistent to me to allow this for all function bodies, so that you could leave out the return if the body consists of a single expression:

func stitch(first: String, second: String) -> String { joiner(first: first, second: second) }

Swift has some other syntactic shortcuts that would unfortunately make the C#/Java style shorthand ambiguous in some cases (particularly with accessors in properties), but the brace approach should work and is consistent with another part of the language today.


(Nikita Leonov) #3

It seems that there are two asks in place. One is an ability to define functions as single expressions. Another ask is to implicitly pass function arguments into the expression in case if inputs & outputs of an expression matching function signature, so the following can be possible.

func makeBFromA(a: A) -> B = aToB
func aToB(a: A) -> B { ... }

I didn't know this is a thing in C#, but definitely common in Haskell and allows to reduce a boilerplate without sacrificing readability. Is something like this potentially can be accommodated by Swift too?


(Benjamin Mayo) #4

Is there a technical/grammar reason why computed property getters require the return keyword?


(Adrian Zubarev) #5

I don't know the technical reasons, but my proposal wasn't even allowed to go into review back then, and I would like to link this comment from @Chris_Lattner3:


(Jens Ayton) #6

If that is added, I think it would also make sense to allow property definitions like:

protocol Foo ...

private var _foo: FooImplementation
public var foo: Foo { get } = _foo