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      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.