# Avoid curly brackets on single line bodies and computed properties

**URL:** <https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954>\
**Category:** Discussion\
**Created:** [September 19, 2019, 7:56am UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954 "2019-09-19T07:56:12Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![elect86](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/elect86/32/8816_2.png) [@elect86](https://forums.swift.org/u/elect86)\
**Post date:** [September 19, 2019, 7:56am UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/1 "2019-09-19T07:56:12Z")

</div>

As titled, coming from Kotlin, this is hurting my eyes

```
public var elements: [Bool] {
    return [x, y]
}

public func makeIterator() -> IndexingIterator<Array<Bool>> {
    return elements.makeIterator()
}

public var debugDescription: String {
    return String(describing: type(of: self)) + "(\(x), \(y))"
}

public func hash(into hasher: inout Hasher) {
    hasher.combine(SGLMath.hash(x.hashValue, y.hashValue))
}

public static func ==(v1: Vector2b, v2: Vector2b) -> Bool {
    return v1.x == v2.x && v1.y == v2.y
}

public var r: Bool {
    get {
        return x
    }
    set {
        x = newValue
    }
}

```

I'd love to have the possibility to simply skip curly brackets for single line bodies and computed properties

```
public var elements: [Bool] = [x, y]

public func makeIterator() -> IndexingIterator<Array<Bool>> = elements.makeIterator()

public var debugDescription: String = String(describing: type(of: self)) + "(\(x), \(y))"

public func hash(into hasher: inout Hasher) =
    hasher.combine(SGLMath.hash(x.hashValue, y.hashValue))

public static func ==(v1: Vector2b, v2: Vector2b) -> Bool =
    v1.x == v2.x && v1.y == v2.y

public var r: Bool
    get() = x
    set {
        x = newValue
    }

```

I tried to search but I didnt find anything about

---

<div class="post-metadata">

**Author:** ![Joanna\_Carter](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joanna_carter/32/1581_2.png) [@Joanna\_Carter](https://forums.swift.org/u/Joanna_Carter)\
**Post date:** [September 19, 2019, 8:43am UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/2 "2019-09-19T08:43:47Z")

</div>

In your example, for the `elements` var, both declarations are valid but with different semantics

```swift
  var elements: [Bool]
  {
    return [true, false]
  }

```

… is a readonly var, whereas

```swift
  public var elements: [Bool] = [true, false]

```

… is a readwrite var, initialised at declaration, which can also be shortened to

```swift
  public var elements = [true, false]

```

---

<div class="post-metadata">

**Author:** ![jawbroken](https://avatars.discourse-cdn.com/v4/letter/j/cc9497/32.png) [@jawbroken](https://forums.swift.org/u/jawbroken)\
**Post date:** [September 19, 2019, 12:26pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/3 "2019-09-19T12:26:30Z")

</div>

With the recent change to allow [implicit returns from single-expression functions](https://github.com/apple/swift-evolution/blob/master/proposals/0255-omit-return.md), you can already freely write these as

```swift
public var elements: [Bool] { [x, y] }

```

and similar, which is very hard to beat for concision. I can't see the point of adding another syntax for this.

---

<div class="post-metadata">

**Author:** ![CTMacUser](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ctmacuser/32/1802_2.png) [@CTMacUser](https://forums.swift.org/u/CTMacUser)\
**Post date:** [September 19, 2019, 4:11pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/4 "2019-09-19T16:11:25Z")

</div>

If it's not in an extension, you can make it read-only, as a stored variable:

```
public let elements: [Bool] = [true, false]

```

The braces (on a `var`) distinguish between a stored property and one that computes on demand but doesn't use up storage.

---

<div class="post-metadata">

**Author:** ![GetSwifty](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/getswifty/32/39108_2.png) [@GetSwifty](https://forums.swift.org/u/GetSwifty)\
**Post date:** [September 19, 2019, 5:42pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/5 "2019-09-19T17:42:56Z")

</div>

I deal with the same kind of frustrations (in both directions) when switching between the Swift and Kotlin.

As others have mentioned, some of your examples can be optimized but not others. My perception is removing much more syntax in Swift will encounter significant pushback from the community (see [SE-0257: Eliding commas from multiline expression lists - #190 by Braden\_Scothern](https://forums.swift.org/t/se-0257-eliding-commas-from-multiline-expression-lists/22889/190) and [Allow function definitions to omit parentheses if no parameters - #5 by allevato](https://forums.swift.org/t/allow-function-definitions-to-omit-parentheses-if-no-parameters/27605/5) )

One thing to keep in mind as a (non-satisfying) reason is how Kotlin treats _everything_ as an expression, while Swift has semantic differences between Properties, Functions, Methods, and Closures differently. That, along with a more complex memory-management system I believe means some of the syntactic sugar you get for free in Kotlin is significantly complex to implement in Swift.

Swift is also designed for clarity and safety, while Kotlin sacrifices some amount of those for a more flexible and script-like syntax. So although I would love to do things in Swift like this:

```swift
func add(_ left: Int, _ right: Int) = left + right
func add1(to value: Int) = add(value, 1)
func addIf0(value: Int) = switch isAllowed {
    case 0: add1(to: value)
    default: value
}

```

there are reasonable arguments that it's much less clear what's happening, and therefore less safe.

Anyway, my guess is that type of syntax isn't coming to Swift anytime soon, just like `static` properties/methods, `enum` associated values, and turnery statements probably aren't coming to Kotlin. 😞

---

<div class="post-metadata">

**Author:** ![ExFalsoQuodlibet](https://avatars.discourse-cdn.com/v4/letter/e/bbce88/32.png) [@ExFalsoQuodlibet](https://forums.swift.org/u/ExFalsoQuodlibet)\
**Post date:** [September 20, 2019, 8:46am UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/6 "2019-09-20T08:46:19Z")

</div>

As noted by @GetSwifty, there are substantial differences between Swift and Kotlin that make harder for Swift to push syntactic sugar too far.

Fortunately, the proposal linked by @jawbroken already makes easier on the eyes single expression functions, improving consistency between named functions and lambdas.

That being said, I disagree with the improvements in readability and understandability achieved by replacing `{}` with `=`: I think it's a lot clearer to wrap the body of a function in curly braces than to "assign" a single expression to the function. But even if it wasn't, I don't see profound differences once you can skip the `return`, which is to me the real offender. For example, I don't see how

```swift
public func hash(into hasher: inout Hasher) {
    hasher.combine(SGLMath.hash(x.hashValue, y.hashValue))
}

```

is hurting your eyes more than the `=` counterpart. Something that could be added is the type inference on computed properties, for example:

```swift
public var debugDescription {
    String(describing: type(of: self)) + "(\(x), \(y))"
}

```

would be better, the `: String` is redundant (from a readability standpoint), but something similar is achieved with `.init`, like:

```swift
public var debugDescription: String {
    .init(describing: type(of: self)) + "(\(x), \(y))"
}

```

so a nice balance was achieved by the aforementioned proposal.

---

<div class="post-metadata">

**Author:** ![elect86](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/elect86/32/8816_2.png) [@elect86](https://forums.swift.org/u/elect86)\
**Post date:** [September 20, 2019, 9:10am UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/7 "2019-09-20T09:10:20Z")

</div>

> [@jawbroken](#):
>
> With the recent change to allow [implicit returns from single-expression functions](https://github.com/apple/swift-evolution/blob/master/proposals/0255-omit-return.md), you can already freely write these as
> 
> ```swift
> public var elements: [Bool] { [x, y] }
> 
> ```
> 
> and similar, which is very hard to beat for concision. I can't see the point of adding another syntax for this.

> [@ExFalsoQuodlibet](#):
>
> That being said, I disagree with the improvements in readability and understandability achieved by replacing `{}` with `=`: I think it's a lot clearer to wrap the body of a function in curly braces than to "assign" a single expression to the function. But even if it wasn't, I don't see profound differences once you can skip the `return`, which is to me the real offender. For example, I don't see how
> 
> ```swift
> public func hash(into hasher: inout Hasher) {
> hasher.combine(SGLMath.hash(x.hashValue, y.hashValue))
> }
> 
> ```
> 
> is hurting your eyes more than the `=` counterpart. Something that could be added is the type inference on computed properties, for example:
> 
> ```swift
> public var debugDescription {
> String(describing: type(of: self)) + "(\(x), \(y))"
> }
> 
> ```
> 
> would be better, the `: String` is redundant (from a readability standpoint), but something similar is achieved with `.init`, like:
> 
> ```swift
> public var debugDescription: String {
> .init(describing: type(of: self)) + "(\(x), \(y))"
> }
> 
> ```
> 
> so a nice balance was achieved by the aforementioned proposal.

Auto-formatting would always put that on new line and consume 3 lines instead 1 (for shortest bodies).

Of course it'd be optional, like in Kotlin, so that if you like wrapping always between brackets, you can continue doing so

---

<div class="post-metadata">

**Author:** ![jawbroken](https://avatars.discourse-cdn.com/v4/letter/j/cc9497/32.png) [@jawbroken](https://forums.swift.org/u/jawbroken)\
**Post date:** [September 20, 2019, 12:33pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/8 "2019-09-20T12:33:55Z")

</div>

It's not the fault of the language if whatever auto-formatting tools you are using are mangling your code in ways you don't prefer, and I really don't think that new redundant syntax should be added just to stop them from doing that.

---

<div class="post-metadata">

**Author:** ![elect86](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/elect86/32/8816_2.png) [@elect86](https://forums.swift.org/u/elect86)\
**Post date:** [September 20, 2019, 1:23pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/9 "2019-09-20T13:23:52Z")

</div>

Kind of, since I'd like to have the possibility to skip the brackets completely

My observation was in reply of one the quoted comments suggesting the "workaround"

---

<div class="post-metadata">

**Author:** ![Max\_Howell1](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/max_howell1/32/10049_2.png) [@Max\_Howell1](https://forums.swift.org/u/Max_Howell1)\
**Post date:** [September 20, 2019, 1:33pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/10 "2019-09-20T13:33:41Z")

</div>

Could be:

```
public var elements: [Bool] <- [true, false]

```

And of course, the type could be inferred here also. Though maybe that is going too far.

```
public var elements <- [true, false]

```

---

<div class="post-metadata">

**Author:** ![Pampel](https://avatars.discourse-cdn.com/v4/letter/p/3da27b/32.png) [@Pampel](https://forums.swift.org/u/Pampel)\
**Post date:** [September 20, 2019, 2:27pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/11 "2019-09-20T14:27:58Z")

</div>

I'm not very keen on this - purely from the point of reading code, it makes it somewhat unclear whether you are assigning a function/expression or the result of executing the function to the variable. Obviously you can tell from the type and, sometimes, the body, which it is - but I'm not sure the extra effort required and potential for confusing people new to the language is worth it.

I find...

```
public var debugDescription: String = String(describing: type(of: self)) + "(\(x), \(y))"

```

...to be the most potentially confusing. Surrounding the code in brackets makes it totally unambiguous that this will be evaluated every time you call `debugDescription`, rather than...when the object is instantiated? When it's first called? Every time?

---

<div class="post-metadata">

**Author:** ![Joanna\_Carter](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joanna_carter/32/1581_2.png) [@Joanna\_Carter](https://forums.swift.org/u/Joanna_Carter)\
**Post date:** [September 20, 2019, 3:17pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/12 "2019-09-20T15:17:58Z")

</div>

What you describe here is a var that has an initial value, but which can also be assigned to; it will be evaluated once for the initial assignment.

On the other hand :

```swift
public var debugDescription: String
{
  return String(describing: type(of: self)) + "(\(x), \(y))"
}

```

… will be evaluated every time it is called.

```swift
public lazy var debugDescription: String = String(describing: type(of: self)) + "(\(x), \(y))"

```

… will be evaluated once only, on first call.

---

<div class="post-metadata">

**Author:** ![GetSwifty](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/getswifty/32/39108_2.png) [@GetSwifty](https://forums.swift.org/u/GetSwifty)\
**Post date:** [September 20, 2019, 5:07pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/13 "2019-09-20T17:07:50Z")

</div>

> [@ExFalsoQuodlibet](#):
>
> replacing `{}` with `=` :

Just to be clear, Kotlin doesn't replace brackets, it allows you to use either

Given Swift's opinionated standardization, I think I agree allowing `=` in a function definition is confusing and easily abused. However I also find it quite elegant in Kotlin to do things like

```swift
fun makeFullName() = "$firstName $lastName"
// or 
val fullName: String get() = "$firstName $lastName"

```

I especially like it when using `when`, e.g. for an enum:

```swift
fun makeSizeLabel(size: SizeEnum) = when(size) {
    SizeEnum.SMALL -> "Small"
    SizeEnum.MEDIUM -> "Medium"
    SizeEnum.LARGE -> "Large"
}

```

Yes you can look at it as muddling the definition of a function/method, and I used to agree. What changed my mind for things like the above is taking it to mean "`makeFullName() = ThisExpression`".

This is why Kotlin's "everything is an expression" construct IMO means it makes sense in Kotlin, and may not make sense in Swift. I don't think there's an existing analogy you can intuit for what `func thing() =` would mean.

Still, personally I would still like a way for single expressions to be written more concisely in Swift. Maybe something like

```swift
func fullName() -> String in "\(firstName) \(lastName)"

```

---

<div class="post-metadata">

**Author:** ![ExFalsoQuodlibet](https://avatars.discourse-cdn.com/v4/letter/e/bbce88/32.png) [@ExFalsoQuodlibet](https://forums.swift.org/u/ExFalsoQuodlibet)\
**Post date:** [September 20, 2019, 5:52pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/14 "2019-09-20T17:52:14Z")

</div>

> [@GetSwifty](#):
>
> Still, personally I would still like a way for single expressions to be written more concisely in Swift. Maybe something like
> 
> ```swift
> func fullName() -> String in "\(firstName) \(lastName)"
> 
> ```

I really don’t see how this form is more concise than

```swift
func fullName() -> String { "\(firstName) \(lastName)" }

```

also, conciseness isn’t everything, I like concise, expressive code, but not a the cost of potential ambiguity and less approachability.

Still, I like the idea that things like `if` and `switch` should be expressions (not everything, though, for example `guard` is great as it is, and it’s one of the things I miss the most in Kotlin): if they were, you could drop the ‘return’, which seem to me the real offender to me, that is, a lot of additional characters that are redundant and add noise.

---

<div class="post-metadata">

**Author:** ![GetSwifty](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/getswifty/32/39108_2.png) [@GetSwifty](https://forums.swift.org/u/GetSwifty)\
**Post date:** [September 20, 2019, 6:08pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/15 "2019-09-20T18:08:03Z")

</div>

> [@ExFalsoQuodlibet](#):
>
> `guard` is great as it is, and it’s one of the things I miss the most in Kotlin

Ditto!

The more concise way would be

```swift
func fullName() in "\(firstName) \(lastName)"

```

but my guess is an inferred Type for a function result would see a lot of pushback.

A couple brackets isn't a huge deal, but that's also true of parens for `if/switch` statements among other things. It wouldn't be earth shattering, but I would prefer the ergonomics in some cases.

---

<div class="post-metadata">

**Author:** ![elect86](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/elect86/32/8816_2.png) [@elect86](https://forums.swift.org/u/elect86)\
**Post date:** [September 20, 2019, 6:12pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/16 "2019-09-20T18:12:19Z")

</div>

> [@GetSwifty](#):
>
> Given Swift's opinionated standardization, I think I agree allowing `=` in a function definition is confusing and easily abused.

I guess you have a valid point there..

> [@ExFalsoQuodlibet](#):
>
> Still, I like the idea that things like `if` and `switch` should be expressions (not everything, though, for example `guard` is great as it is, and it’s one of the things I miss the most in Kotlin): if they were, you could drop the ‘return’, which seem to me the real offender to me, that is, a lot of additional characters that are redundant and add noise.

It's indeed pretty plain and natural extracting the `return` at the end

```swift
return if(cond) a else b

```

```swift
return when(cond) {
    a -> x
    b -> y
}

```

Regarding `guard` I find the concept really fascinating, but the implementation quite poor..  
having to explicitly type every single time `else { ... return }` is quite verbose and annoying.. I'd have expected a default `nil` for `Optional`s and plain return with `Void` (maybe passing a string in a autoclosure)

---

<div class="post-metadata">

**Author:** ![GetSwifty](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/getswifty/32/39108_2.png) [@GetSwifty](https://forums.swift.org/u/GetSwifty)\
**Post date:** [September 20, 2019, 6:25pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/17 "2019-09-20T18:25:31Z")

</div>

> [@elect86](#):
>
> having to explicitly type every single time `else { ... return }` is quite verbose and annoying

Once you understand what's happening, I agree it's verbose. However, if you're new to programming or new to swift, I don't think it would be possible to intuit what's happening. If I came to Swift and saw

```swift
func doAThing() -> Thing? {
    guard thing.isReady 

    return thing.doTheThing()
}

```

I would find it difficult to guess what's happening.  
v.s.

```swift
func doAThing() -> Thing? {
    guard thing.isReady { return nil }

    return thing.doTheThing()
}

```

IMO it's much clearer and easy to reason about what might be happening, and makes it clear that author's intention is to return nil if `thing` isn't ready.

---

<div class="post-metadata">

**Author:** ![elect86](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/elect86/32/8816_2.png) [@elect86](https://forums.swift.org/u/elect86)\
**Post date:** [September 20, 2019, 6:36pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/18 "2019-09-20T18:36:18Z")

</div>

I dont know, for me the keyword itself `guard` is quite significant and self-explanatory

But maybe it's because I tend to associate it to a sort of a runtime `assert`

---

<div class="post-metadata">

**Author:** ![ExFalsoQuodlibet](https://avatars.discourse-cdn.com/v4/letter/e/bbce88/32.png) [@ExFalsoQuodlibet](https://forums.swift.org/u/ExFalsoQuodlibet)\
**Post date:** [September 20, 2019, 6:40pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/19 "2019-09-20T18:40:30Z")

</div>

> [@elect86](#):
>
> I'd have expected a default `nil` for `Optional` s and plain return with `Void`

Implicitly retuning `nil` for functions returning ‘Optional` would be really bad to me, and profoundly contrary to Swift core values and patterns.

I guess returning implicitly for functions returning `void` would be fine, but a little confusing for newcomers.

---

<div class="post-metadata">

**Author:** ![elect86](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/elect86/32/8816_2.png) [@elect86](https://forums.swift.org/u/elect86)\
**Post date:** [September 20, 2019, 6:51pm UTC](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954/20 "2019-09-20T18:51:01Z")

</div>

Having to explicitly write the `else` branch empty the usage of guard in the first place, for me

[Next page](https://forums.swift.org/t/avoid-curly-brackets-on-single-line-bodies-and-computed-properties/28954.md?page=2)
