UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

Forums > 100 Days of SwiftUI

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

or

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

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

1      

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

2      

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")
}

2      

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.

2      

Appreciate the thoughtful answers!

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.