Swift style guide

Hi,

I have some doubts regarding Swift Coding style. My apologies if this has already been asked, I would be happy to follow any existing threads. Many thanks.

Questions:

  1. Are there any style guides for Swift? I do understand it can be subjective, are there any guidelines or widely followed approaches?
  2. In Apple's documentation and presentations I see the option 1 (see code below) being used, is this the preferred style or is it used because of horizontal space constraints on the documentation window / presentation slides?
  3. I use Option 2 (see code below), is that an reasonable option (or is there any preferred style)?

Code

I have given below sample code:

class Car {
    var name: String
    var price: Int
    
    //Option 1:
    init(
        name: String,
        price: Int
    ) {
        self.name = name
        self.price = price
    }

    //Option 2:
    func update(name: String,
                price: Int) {
        self.name = name
        self.price = price
    }
}

For lines that need wrapping, I follow the style guide from Google (which corresponds with option 1): Swift Style Guide

2 Likes

@svanimpe Thanks for a lot for the link.

My style has always been the same for any language with curly braces…

class Car
{
  var name: String

  var price: Int
    
  init(name: String, price: Int)
  {
    self.name = name
    
    self.price = price
  }

  func update(name: String, price: Int)
  {
    self.name = name

    self.price = price
  }
}
4 Likes

I know you're asking for official guidelines, but for curiosity's sake I'll describe how I do it.

In your example, I would write:

/// I put three slashes above every "unit"
/// where a "unit" is non-rigorously defined
/// as simply whatever looks to me like a unit -
/// this serves a visual aid for parsing the code at a glance
/// and once in a while when it seems appropriate I put a comment
class Car {

    ///
    var name: String
    var price: Int
    
    ///
    init
        (name: String,
         price: Int) {

        ///
        self.name = name
        self.price = price
    }

    ///
    func update
        (name: String,
         price: Int) {

        ///
        self.name = name
        self.price = price
    }

    ///
    func someLongFunctionNameWithInputsAndGenericParamsAndReturnValue
        <Generic: Parameters,
         GetTheirOwnLine: And>
        (theInputs: Array<Generic>,
         areEasilyReadable: Bool,
         becauseTheirHorizontalLocation: CGFloat,
         isNotDependentOnTheLengthOfTheFunctionName: Bool)
    async throws -> (effectsAndReturnValue: String, areOnTheirOwnLine: String)
        where Generic.WhereClause: GetsItsOwnLineToo {

        ///
        ("Similar approach for formatting", "within the function body")
    }

    ///
    func shortFunctionSignatures () -> CanBeJustOneLine {
        ...
    }
}

One result is that almost all of my code could be comfortably viewed on a vertical iPhone.

1 Like

Option 2 doesn't scale to generics.

  func update<Windschutzscheibe: Sequence, Klappscheinwerfer: Collection, Anhängerkupplung>(windschutzscheibe: Windschutzscheibe,
                                                                                            klappscheinwerfer: Klappscheinwerfer,
                                                                                            anhängerkupplung: Anhängerkupplung) where Windschutzscheibe.Element == Klappscheinwerfer.Element, Klappscheinwerfer.Index == Anhängerkupplung {
4 Likes

Thanks @anon9791410 Yes that is a problem I faced while using long function names / generics

I have a question for @somu and @jeremyabannister. Both of you proposed coding styles similar to the following:

func update(
    name: String,
    price: Int) {
    ...
}

I wonder how do you do it in Xcode? After you input "func updte(" and press Return key, xcode don't indent automatically. Do you have to press Tab key manually? That seems very inconvenient to me.

@rayx When you press return after ( it should indent on the next line. (downloading Xcode now, so will try it and confirm but should work as for Option 1)

I normally press Control + I on the line I want to format (don't press +, I mean Control and I)

On Xcode Control + I does the the code formatting automatically (depends on the above line, option 1 and option 2 seem to work fine with it)

You can also multi select lines and press Control + I

Thanks for your answer. But no, it doesn't indent. I tried it before I posted the question.

I didn't know Control+I and tried it just now, but it did nothing in my experiment. I googled it and found a comment which suggested it doesn't necessarily change code:

control-I does not reformat the code, it merely "balances" each line. so, it does not enforce all the necessary newlines, indentation and so on that is part of the standard idiom for control structures in Swift. (confusingly, Xcode has the ability to automatically format your Swift as you type, but there's no button to "fix" batches of it later!)

My coding style is also similar to what's described in the. guide, but I just put the where keyword on the same line as the closing parenthesis:

public func index<Elements: Collection, Element>(
  of element: Element,
  in collection: Elements
- ) -> Elements.Index?
- where
+ ) -> Elements.Index? where
  Elements.Element == Element,
  Element: Equatable
{  // GOOD.
  for current in elements {
    // ...
  }
}

I know this isn't the exact question asked, but my opinion is for your own projects to use either apple/swift-format or nicklockwood/SwiftFormat and their defaults.

Both defaults are sensible, they ensure you're consistent, and most importantly you don't have to make decisions about which is "better".

2 Likes

Thanks a lot @Scott, pardon my ignorance, can apple/swift-format be integrated into Xcode?
I would like it to suggest or warn when my Xcode project code doesn't adhere to the guidelines?

I think the answer to that is "kind of".

I used GitHub - ruiaureliano/X-SwiftFormat: X-SwiftFormat extension for Xcode a while ago which gave the ability to trigger formatting a file from Xcode. I don't think it would show you warnings though.

Xcode's source editor extensions, and all of their plugin capabilities in general, leave much to be desired.

1 Like

Thanks a lot @Scott I will give it a try

1 Like

In Xcode 15, you can format the function arguments.

  1. Place cursor on any of the argument labels
  2. Press ^ M

This follows option 1.

I love this feature!!!! thank you to the team who worked on this, would save me a ton of time!!!

1 Like