WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: What is the preferred way of writing a one-line function?

Forums > 100 Days of SwiftUI

func name() {
  print("Do some work")


func name() { print("Do some work") }

I've seen people use both variations and got curious about which of them is clearer.


It's a) personal preference or b) what your company requires you to do in their guidline when you're coding for them.


While stylistically the choice is yours (unless you have style guidelines that you follow, for yourself or in your organisation), as both create correct code. I follow the first example for a couple of reasons.

The first is easier (just a tiny fraction less work) as you do not have to adjust the layout before adding more lines.

It is likely that you will be writing a lot more functions in the first style, so much so that the second style will start to look strange when you use it.

It is upto you, just be consistent in your code.

To answer your question, in my opinion the first one is clearer.

func name() {
  print("Do some work")


While you probably will not write too many one line functions (as usually want to do some logic or code that repeats), however as above your preference etc. You more likely to do as a closure eg

.onAppear { print("Do some work") }
// or
.onAppear {
  print("Do some work")

In this case i would choose inline and if it had more logic then move it to a method as the inline read (to me) easier.


Appreciate the thoughtful answers!


Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.