2

In C#, there's a feature called 'Expression-bodied members' which lets you use an expression to satisfy the body of a function/method or property. For instance, instead of writing these...

void PushItem(object item) {
    someStack.push(item)
}

int AddFour(int x) {
    return x + 4;
}

int SomeProperty{
    get{ return _someProperty; }
    set{ _someProperty = value; }
}

You can just write these...

void PushItem(object item) => someStack.push(item)

int AddFour(int x) => x + 4;

int SomeProperty{
    get => _someProperty;
    set => _someProperty = value;
}

Wondering if Swift has anything similar. It really keeps the code nice, lean and readable.

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • as far as i know, nope swift don't have a similar thing – Mohmmad S Sep 21 '18 at 01:56
  • The feature is relatively new and currently only exists in C# (other languages don't have this kind of syntax). It's a syntactic sugar to simplify property getter and setters declaration. – Tetsuya Yamamoto Sep 21 '18 at 01:59
  • Damn! Microsoft uses the same `=>` for both lambdas (Swift closures) as well as Expression-Bodied Members, so I was hoping Swift would jump on the bandwagon and do the same/similar. They seem to be racing back and forth for parity these days. – Mark A. Donohoe Sep 21 '18 at 02:00
  • @TetsuyaYamamoto, it's not just properties. It's *anything* that supports a body which can be represented by a single statement. It really simplifies things a lot. – Mark A. Donohoe Sep 21 '18 at 02:00
  • I'd argue that `SomeProperty` and `PushItem` are good approaches, since they seem to be masking a shared mutable state (one of the worst kind of stared stuff). – Cristik Sep 21 '18 at 04:46
  • Not following your comment, @Cristik. Was that directed at me? Also, you're referring to completely made-up names where I was just showing the syntactical difference between a method, a function and a property. They're exactly the same between the two. Just one imho appears cleaner thanks to the syntax. – Mark A. Donohoe Sep 21 '18 at 18:48
  • @MarqueIV I was referring to the implementation rather than the names, as this kind of constructs seem to bring implicit usage of shared state, at least from what I see from the examples above. – Cristik Sep 21 '18 at 19:37
  • Oh, that's just made-up code showing the difference between using braces with an expression (and a return if applicable) vs the simplicity of the `=>` operator. You can put any single expression there. Again, this is just made up crap that I typed. – Mark A. Donohoe Dec 10 '21 at 19:52

1 Answers1

1

Looking into swift documentation in closures section,

I have never came across something like this,

Even on the side menu there are no signs of anything similar to that

Swift doesn't support that feature and its not clear if it will be in the future.

Read more about Swift here

Mohmmad S
  • 5,001
  • 4
  • 18
  • 50