Code Monkey home page Code Monkey logo

swift-style-guide's Introduction

The Official Kodeco Swift Style Guide.

Updated for Swift 5

This style guide is different from others you may see, because the focus is centered on readability for print and the web. We created this style guide to keep the code in our books, tutorials, and starter kits nice and consistent — even though we have many different authors working on the books.

Our overarching goals are clarity, consistency and brevity, in that order.

Table of Contents

Correctness

Strive to make your code compile without warnings. This rule informs many style decisions such as using #selector types instead of string literals.

Using SwiftLint

When writing for Kodeco, you are strongly encouraged — perhaps even required, depending on your team — to use our SwiftLint configuration. See the SwiftLint Policy for more information.

Naming

Descriptive and consistent naming makes software easier to read and understand. Use the Swift naming conventions described in the API Design Guidelines. Some key takeaways include:

  • striving for clarity at the call site
  • prioritizing clarity over brevity
  • using camelCase (not snake_case)
  • using UpperCamelCase for types and protocols, lowerCamelCase for everything else
  • including all needed words while omitting needless words
  • using names based on roles, not types
  • sometimes compensating for weak type information
  • striving for fluent usage
  • beginning factory methods with make
  • naming methods for their side effects
    • verb methods follow the -ed, -ing rule for the non-mutating version
    • noun methods follow the formX rule for the mutating version
    • boolean types should read like assertions
    • protocols that describe what something is should read as nouns
    • protocols that describe a capability should end in -able or -ible
  • using terms that don't surprise experts or confuse beginners
  • generally avoiding abbreviations
  • using precedent for names
  • preferring methods and properties to free functions
  • casing acronyms and initialisms uniformly up or down
  • giving the same base name to methods that share the same meaning
  • avoiding overloads on return type
  • choosing good parameter names that serve as documentation
  • preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates
  • labeling closure and tuple parameters
  • taking advantage of default parameters

Prose

When referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible.

  1. Write the method name with no parameters. Example: Next, you need to call addTarget.
  2. Write the method name with argument labels. Example: Next, you need to call addTarget(_:action:).
  3. Write the full method name with argument labels and types. Example: Next, you need to call addTarget(_: Any?, action: Selector?).

For the above example using UIGestureRecognizer, 1 is unambiguous and preferred.

Pro Tip: You can use Xcode's jump bar to lookup methods with argument labels. If you’re particularly good at mashing lots of keys simultaneously, put the cursor in the method name and press Shift-Control-Option-Command-C (all 4 modifier keys) and Xcode will kindly put the signature on your clipboard.

Methods in Xcode jump bar

Class Prefixes

Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as RW. If two names from different modules collide you can disambiguate by prefixing the type name with the module name. However, only specify the module name when there is possibility for confusion, which should be rare.

import SomeModule

let myClass = MyModule.UsefulClass()

Delegates

When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.)

Preferred:

func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String)
func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool

Not Preferred:

func didSelectName(namePicker: NamePickerViewController, name: String)
func namePickerShouldReload() -> Bool

Use Type Inferred Context

Use compiler inferred context to write shorter, clear code. (Also see Type Inference.)

Preferred:

let selector = #selector(viewDidLoad)
view.backgroundColor = .red
let toView = context.view(forKey: .to)
let view = UIView(frame: .zero)

Not Preferred:

let selector = #selector(ViewController.viewDidLoad)
view.backgroundColor = UIColor.red
let toView = context.view(forKey: UITransitionContextViewKey.to)
let view = UIView(frame: CGRect.zero)

Generics

Generic type parameters should be descriptive, upper camel case names. When a type name doesn't have a meaningful relationship or role, use a traditional single uppercase letter such as T, U, or V.

Preferred:

struct Stack<Element> { ... }
func write<Target: OutputStream>(to target: inout Target)
func swap<T>(_ a: inout T, _ b: inout T)

Not Preferred:

struct Stack<T> { ... }
func write<target: OutputStream>(to target: inout target)
func swap<Thing>(_ a: inout Thing, _ b: inout Thing)

Language

Use US English spelling to match Apple's API.

Preferred:

let color = "red"

Not Preferred:

let colour = "red"

Code Organization

Use extensions to organize your code into logical blocks of functionality. Each extension should be set off with a // MARK: - comment to keep things well-organized.

Protocol Conformance

In particular, when adding protocol conformance to a model, prefer adding a separate extension for the protocol methods. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.

Preferred:

class MyViewController: UIViewController {
  // class stuff here
}

// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource {
  // table view data source methods
}

// MARK: - UIScrollViewDelegate
extension MyViewController: UIScrollViewDelegate {
  // scroll view delegate methods
}

Not Preferred:

class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
  // all methods
}

Since the compiler does not allow you to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class. This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the author.

For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.

Unused Code

Unused (dead) code, including Xcode template code and placeholder comments should be removed. An exception is when your tutorial or book instructs the user to use the commented code.

Aspirational methods not directly associated with the tutorial whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.

Preferred:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return Database.contacts.count
}

Not Preferred:

override func didReceiveMemoryWarning() {
  super.didReceiveMemoryWarning()
  // Dispose of any resources that can be recreated.
}

override func numberOfSections(in tableView: UITableView) -> Int {
  // #warning Incomplete implementation, return the number of sections
  return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  // #warning Incomplete implementation, return the number of rows
  return Database.contacts.count
}

Minimal Imports

Import only the modules a source file requires. For example, don't import UIKit when importing Foundation will suffice. Likewise, don't import Foundation if you must import UIKit.

Preferred:

import UIKit
var view: UIView
var deviceModels: [String]

Preferred:

import Foundation
var deviceModels: [String]

Not Preferred:

import UIKit
import Foundation
var view: UIView
var deviceModels: [String]

Not Preferred:

import UIKit
var deviceModels: [String]

Spacing

  • Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode and in the Project settings as shown below:

Xcode indent settings

  • Method braces and other braces (if/else/switch/while etc.) always open on the same line as the statement but close on a new line.
  • Tip: You can re-indent by selecting some code (or Command-A to select all) and then Control-I (or Editor ▸ Structure ▸ Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.

Preferred:

if user.isHappy {
  // Do something
} else {
  // Do something else
}

Not Preferred:

if user.isHappy
{
  // Do something
}
else {
  // Do something else
}
  • There should be one blank line between methods and up to one blank line between type declarations to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.

  • There should be no blank lines after an opening brace or before a closing brace.

  • Closing parentheses should not appear on a line by themselves.

Preferred:

let user = try await getUser(
  for: userID,
  on: connection)

Not Preferred:

let user = try await getUser(
  for: userID,
  on: connection
)
  • Colons always have no space on the left and one space on the right. Exceptions are the ternary operator ? :, empty dictionary [:] and #selector syntax addTarget(_:action:).

Preferred:

class TestDatabase: Database {
  var data: [String: CGFloat] = ["A": 1.2, "B": 3.2]
}

Not Preferred:

class TestDatabase : Database {
  var data :[String:CGFloat] = ["A" : 1.2, "B":3.2]
}
  • Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.

  • Avoid trailing whitespaces at the ends of lines.

  • Add a single newline character at the end of each file.

Comments

When they are needed, use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted.

Avoid block comments inline with code, as the code should be as self-documenting as possible. Exception: This does not apply to those comments used to generate documentation.

Avoid the use of C-style comments (/* ... */). Prefer the use of double- or triple-slash.

Classes and Structures

Which one to use?

Remember, structs have value semantics. Use structs for things that do not have an identity. An array that contains [a, b, c] is really the same as another array that contains [a, b, c] and they are completely interchangeable. It doesn't matter whether you use the first array or the second, because they represent the exact same thing. That's why arrays are structs.

Classes have reference semantics. Use classes for things that do have an identity or a specific life cycle. You would model a person as a class because two person objects are two different things. Just because two people have the same name and birthdate, doesn't mean they are the same person. But the person's birthdate would be a struct because a date of 3 March 1950 is the same as any other date object for 3 March 1950. The date itself doesn't have an identity.

Sometimes, things should be structs but need to conform to AnyObject or are historically modeled as classes already (NSDate, NSSet). Try to follow these guidelines as closely as possible.

Example definition

Here's an example of a well-styled class definition:

class Circle: Shape {
  var x: Int, y: Int
  var radius: Double
  var diameter: Double {
    get {
      return radius * 2
    }
    set {
      radius = newValue / 2
    }
  }

  init(x: Int, y: Int, radius: Double) {
    self.x = x
    self.y = y
    self.radius = radius
  }

  convenience init(x: Int, y: Int, diameter: Double) {
    self.init(x: x, y: y, radius: diameter / 2)
  }

  override func area() -> Double {
    return Double.pi * radius * radius
  }
}

extension Circle: CustomStringConvertible {
  var description: String {
    return "center = \(centerString) area = \(area())"
  }
  private var centerString: String {
    return "(\(x),\(y))"
  }
}

The example above demonstrates the following style guidelines:

  • Specify types for properties, variables, constants, argument declarations and other statements with a space after the colon but not before, e.g. x: Int, and Circle: Shape.
  • Define multiple variables and structures on a single line if they share a common purpose / context.
  • Indent getter and setter definitions and property observers.
  • Don't add modifiers such as internal when they're already the default. Similarly, don't repeat the access modifier when overriding a method.
  • Organize extra functionality (e.g. printing) in extensions.
  • Hide non-shared, implementation details such as centerString inside the extension using private access control.

Use of Self

For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.

Use self only when required by the compiler (in @escaping closures, or in initializers to disambiguate properties from arguments). In other words, if it compiles without self then omit it.

Computed Properties

For conciseness, if a computed property is read-only, omit the get clause. The get clause is required only when a set clause is provided.

Preferred:

var diameter: Double {
  return radius * 2
}

Not Preferred:

var diameter: Double {
  get {
    return radius * 2
  }
}

Final

Marking classes or members as final in tutorials can distract from the main topic and is not required. Nevertheless, use of final can sometimes clarify your intent and is worth the cost. In the below example, Box has a particular purpose and customization in a derived class is not intended. Marking it final makes that clear.

// Turn any generic type into a reference type using this Box class.
final class Box<T> {
  let value: T
  init(_ value: T) {
    self.value = value
  }
}

Function Declarations

Keep short function declarations on one line including the opening brace:

func reticulateSplines(spline: [Double]) -> Bool {
  // reticulate code goes here
}

For functions with long signatures, put each parameter on a new line and add an extra indent on subsequent lines:

func reticulateSplines(
  spline: [Double], 
  adjustmentFactor: Double,
  translateConstant: Int, 
  comment: String
) -> Bool {
  // reticulate code goes here
}

Don't use (Void) to represent the lack of an input; simply use (). Use Void instead of () for closure and function outputs.

Preferred:

func updateConstraints() -> Void {
  // magic happens here
}

typealias CompletionHandler = (result) -> Void

Not Preferred:

func updateConstraints() -> () {
  // magic happens here
}

typealias CompletionHandler = (result) -> ()

Function Calls

Mirror the style of function declarations at call sites. Calls that fit on a single line should be written as such:

let success = reticulateSplines(splines)

If the call site must be wrapped, put each parameter on a new line, indented one additional level:

let success = reticulateSplines(
  spline: splines,
  adjustmentFactor: 1.3,
  translateConstant: 2,
  comment: "normalize the display")

Closure Expressions

Use trailing closure syntax only if there's a single closure expression parameter at the end of the argument list. Give the closure parameters descriptive names.

Preferred:

UIView.animate(withDuration: 1.0) {
  self.myView.alpha = 0
}

UIView.animate(withDuration: 1.0, animations: {
  self.myView.alpha = 0
}, completion: { finished in
  self.myView.removeFromSuperview()
})

Not Preferred:

UIView.animate(withDuration: 1.0, animations: {
  self.myView.alpha = 0
})

UIView.animate(withDuration: 1.0, animations: {
  self.myView.alpha = 0
}) { f in
  self.myView.removeFromSuperview()
}

For single-expression closures where the context is clear, use implicit returns:

attendeeList.sort { a, b in
  a > b
}

Chained methods using trailing closures should be clear and easy to read in context. Decisions on spacing, line breaks, and when to use named versus anonymous arguments is left to the discretion of the author. Examples:

let value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.index(of: 90)

let value = numbers
  .map {$0 * 2}
  .filter {$0 > 50}
  .map {$0 + 10}

Types

Always use Swift's native types and expressions when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed.

Preferred:

let width = 120.0                                    // Double
let widthString = "\(width)"                         // String

Less Preferred:

let width = 120.0                                    // Double
let widthString = (width as NSNumber).stringValue    // String

Not Preferred:

let width: NSNumber = 120.0                          // NSNumber
let widthString: NSString = width.stringValue        // NSString

In drawing code, use CGFloat if it makes the code more succinct by avoiding too many conversions.

Constants

Constants are defined using the let keyword and variables with the var keyword. Always use let instead of var if the value of the variable will not change.

Tip: A good technique is to define everything using let and only change it to var if the compiler complains!

You can define constants on a type rather than on an instance of that type using type properties. To declare a type property as a constant simply use static let. Type properties declared in this way are generally preferred over global constants because they are easier to distinguish from instance properties. Example:

Preferred:

enum Math {
  static let e = 2.718281828459045235360287
  static let root2 = 1.41421356237309504880168872
}

let hypotenuse = side * Math.root2

Note: The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace.

Not Preferred:

let e = 2.718281828459045235360287  // pollutes global namespace
let root2 = 1.41421356237309504880168872

let hypotenuse = side * root2 // what is root2?

Static Methods and Variable Type Properties

Static methods and type properties work similarly to global functions and global variables and should be used sparingly. They are useful when functionality is scoped to a particular type or when Objective-C interoperability is required.

Optionals

Declare variables and function return types as optional with ? where a nil value is acceptable.

Use implicitly unwrapped types declared with ! only for instance variables that you know will be initialized later before use, such as subviews that will be set up in viewDidLoad(). Prefer optional binding to implicitly unwrapped optionals in most other cases.

When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:

textContainer?.textLabel?.setNeedsDisplay()

Use optional binding when it's more convenient to unwrap once and perform multiple operations:

if let textContainer = textContainer {
  // do many things with textContainer
}

Notes: Swift 5.7 introduced new shorthand syntax for unwrapping optionals into shadowed variables:

if let textContainer {
  // do many things with textContainer
}

When naming optional variables and properties, avoid naming them like optionalString or maybeView since their optional-ness is already in the type declaration.

For optional binding, shadow the original name whenever possible rather than using names like unwrappedView or actualLabel.

Preferred:

var subview: UIView?
var volume: Double?

// later on...
if let subview = subview, let volume = volume {
  // do something with unwrapped subview and volume
}

// another example
resource.request().onComplete { [weak self] response in
  guard let self = self else { return }
  let model = self.updateModel(response)
  self.updateUI(model)
}

Not Preferred:

var optionalSubview: UIView?
var volume: Double?

if let unwrappedSubview = optionalSubview {
  if let realVolume = volume {
    // do something with unwrappedSubview and realVolume
  }
}

// another example
UIView.animate(withDuration: 2.0) { [weak self] in
  guard let strongSelf = self else { return }
  strongSelf.alpha = 1.0
}

Lazy Initialization

Consider using lazy initialization for finer grained control over object lifetime. This is especially true for UIViewController that loads views lazily. You can either use a closure that is immediately called { }() or call a private factory method. Example:

lazy var locationManager = makeLocationManager()

private func makeLocationManager() -> CLLocationManager {
  let manager = CLLocationManager()
  manager.desiredAccuracy = kCLLocationAccuracyBest
  manager.delegate = self
  manager.requestAlwaysAuthorization()
  return manager
}

Notes:

  • [unowned self] is not required here. A retain cycle is not created.
  • Location manager has a side-effect for popping up UI to ask the user for permission so fine grain control makes sense here.

Type Inference

Prefer compact code and let the compiler infer the type for constants or variables of single instances. Type inference is also appropriate for small, non-empty arrays and dictionaries. When required, specify the specific type such as CGFloat or Int16.

Preferred:

let message = "Click the button"
let currentBounds = computeViewBounds()
var names = ["Mic", "Sam", "Christine"]
let maximumWidth: CGFloat = 106.5

Not Preferred:

let message: String = "Click the button"
let currentBounds: CGRect = computeViewBounds()
var names = [String]()

Type Annotation for Empty Arrays and Dictionaries

For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.)

Preferred:

var names: [String] = []
var lookup: [String: Int] = [:]

Not Preferred:

var names = [String]()
var lookup = [String: Int]()

NOTE: Following this guideline means picking descriptive names is even more important than before.

Syntactic Sugar

Prefer the shortcut versions of type declarations over the full generics syntax.

Preferred:

var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?

Not Preferred:

var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>

Functions vs Methods

Free functions, which aren't attached to a class or type, should be used sparingly. When possible, prefer to use a method instead of a free function. This aids in readability and discoverability.

Free functions are most appropriate when they aren't associated with any particular type or instance.

Preferred

let sorted = items.mergeSorted()  // easily discoverable
rocket.launch()  // acts on the model

Not Preferred

let sorted = mergeSort(items)  // hard to discover
launch(&rocket)

Free Function Exceptions

let tuples = zip(a, b)  // feels natural as a free function (symmetry)
let value = max(x, y, z)  // another free function that feels natural

Memory Management

Code (even non-production, tutorial demo code) should not create reference cycles. Analyze your object graph and prevent strong cycles with weak and unowned references. Alternatively, use value types (struct, enum) to prevent cycles altogether.

Extending object lifetime

Extend object lifetime using the [weak self] and guard let self = self else { return } idiom. [weak self] is preferred to [unowned self] where it is not immediately obvious that self outlives the closure. Explicitly extending lifetime is preferred to optional chaining.

Preferred

resource.request().onComplete { [weak self] response in
  guard let self = self else {
    return
  }
  let model = self.updateModel(response)
  self.updateUI(model)
}

Not Preferred

// might crash if self is released before response returns
resource.request().onComplete { [unowned self] response in
  let model = self.updateModel(response)
  self.updateUI(model)
}

Not Preferred

// deallocate could happen between updating the model and updating UI
resource.request().onComplete { [weak self] response in
  let model = self?.updateModel(response)
  self?.updateUI(model)
}

Access Control

Full access control annotation in tutorials can distract from the main topic and is not required. Using private and fileprivate appropriately, however, adds clarity and promotes encapsulation. Prefer private to fileprivate; use fileprivate only when the compiler insists.

Only explicitly use open, public, and internal when you require a full access control specification.

Use access control as the leading property specifier. The only things that should come before access control are the static specifier or attributes such as @IBAction, @IBOutlet and @discardableResult.

Preferred:

private let message = "Great Scott!"

class TimeMachine {  
  private dynamic lazy var fluxCapacitor = FluxCapacitor()
}

Not Preferred:

fileprivate let message = "Great Scott!"

class TimeMachine {  
  lazy dynamic private var fluxCapacitor = FluxCapacitor()
}

Control Flow

Prefer the for-in style of for loop over the while-condition-increment style.

Preferred:

for _ in 0..<3 {
  print("Hello three times")
}

for (index, person) in attendeeList.enumerated() {
  print("\(person) is at position #\(index)")
}

for index in stride(from: 0, to: items.count, by: 2) {
  print(index)
}

for index in (0...3).reversed() {
  print(index)
}

Not Preferred:

var i = 0
while i < 3 {
  print("Hello three times")
  i += 1
}


var i = 0
while i < attendeeList.count {
  let person = attendeeList[i]
  print("\(person) is at position #\(i)")
  i += 1
}

Ternary Operator

The Ternary operator, ?: , should only be used when it increases clarity or code neatness. A single condition is usually all that should be evaluated. Evaluating multiple conditions is usually more understandable as an if statement or refactored into instance variables. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use.

Preferred:

let value = 5
result = value != 0 ? x : y

let isHorizontal = true
result = isHorizontal ? x : y

Not Preferred:

result = a > b ? x = c > d ? c : d : y

Golden Path

When coding with conditionals, the left-hand margin of the code should be the "golden" or "happy" path. That is, don't nest if statements. Multiple return statements are OK. The guard statement is built for this.

Preferred:

func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies {
  guard let context = context else {
    throw FFTError.noContext
  }
  guard let inputData = inputData else {
    throw FFTError.noInputData
  }

  // use context and input to compute the frequencies
  return frequencies
}

Not Preferred:

func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies {
  if let context = context {
    if let inputData = inputData {
      // use context and input to compute the frequencies

      return frequencies
    } else {
      throw FFTError.noInputData
    }
  } else {
    throw FFTError.noContext
  }
}

When multiple optionals are unwrapped either with guard or if let, minimize nesting by using the compound version when possible. In the compound version, place the guard on its own line, then indent each condition on its own line. The else clause is indented to match the guard itself, as shown below. Example:

Preferred:

guard 
  let number1 = number1,
  let number2 = number2,
  let number3 = number3 
else {
  fatalError("impossible")
}
// do something with numbers

Not Preferred:

if let number1 = number1 {
  if let number2 = number2 {
    if let number3 = number3 {
      // do something with numbers
    } else {
      fatalError("impossible")
    }
  } else {
    fatalError("impossible")
  }
} else {
  fatalError("impossible")
}

Failing Guards

Guard statements are required to exit in some way. Generally, this should be simple one line statement such as return, throw, break, continue, and fatalError(). Large code blocks should be avoided. If cleanup code is required for multiple exit points, consider using a defer block to avoid cleanup code duplication.

Semicolons

Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line.

Do not write multiple statements on a single line separated with semicolons.

Preferred:

let swift = "not a scripting language"

Not Preferred:

let swift = "not a scripting language";

NOTE: Swift is very different from JavaScript, where omitting semicolons is generally considered unsafe

Parentheses

Parentheses around conditionals are not required and should be omitted.

Preferred:

if name == "Hello" {
  print("World")
}

Not Preferred:

if (name == "Hello") {
  print("World")
}

In larger expressions, optional parentheses can sometimes make code read more clearly.

Preferred:

let playerMark = (player == current ? "X" : "O")

Multi-line String Literals

When building a long string literal, you're encouraged to use the multi-line string literal syntax. Open the literal on the same line as the assignment but do not include text on that line. Indent the text block one additional level.

Preferred:

let message = """
  You cannot charge the flux \
  capacitor with a 9V battery.
  You must use a super-charger \
  which costs 10 credits. You currently \
  have \(credits) credits available.
  """

Not Preferred:

let message = """You cannot charge the flux \
  capacitor with a 9V battery.
  You must use a super-charger \
  which costs 10 credits. You currently \
  have \(credits) credits available.
  """

Not Preferred:

let message = "You cannot charge the flux " +
  "capacitor with a 9V battery.\n" +
  "You must use a super-charger " +
  "which costs 10 credits. You currently " +
  "have \(credits) credits available."

No Emoji

Do not use emoji in your projects. For those readers who actually type in their code, it's an unnecessary source of friction. While it may be cute, it doesn't add to the learning and it interrupts the coding flow for these readers.

No #imageLiteral or #colorLiteral

Likewise, do not use Xcode's ability to drag a color or an image into a source statement. These turn into #colorLiteral and #imageLiteral, respectively, and present unpleasant challenges for a reader trying to enter them based on tutorial text. Instead, use UIColor(red:green:blue) and UIImage(imageLiteralResourceName:).

Organization and Bundle Identifier

Where an Xcode project is involved, the organization should be set to Kodeco and the Bundle Identifier set to com.yourcompany.TutorialName where TutorialName is the name of the tutorial project.

Xcode Project settings

Copyright Statement

The following copyright statement should be included at the top of every source file:

/// Copyright (c) 2023 Kodeco Inc.
/// 
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
/// 
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
/// 
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology.  Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
/// 
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.

Smiley Face

Smiley faces are a very prominent style feature of the Kodeco site! It is very important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The closing square bracket ] is used because it represents the largest smile able to be captured using ASCII art. A closing parenthesis ) creates a half-hearted smile, and thus is not preferred.

Preferred:

:]

Not Preferred:

:)

References

swift-style-guide's People

Contributors

catiecatterwaul avatar colineberhardt avatar djui avatar edekhayser avatar gregheo avatar jasl avatar jawwad avatar jellodiil avatar koenpunt avatar kpacholak avatar leonerd42 avatar lfarah avatar longlene avatar markhim avatar melissayung avatar moayes avatar mrsktcollins avatar orionthewake avatar pitt500 avatar presto95 avatar rayfix avatar rcritz avatar rwenderlich avatar sameoldmadness avatar sammyd avatar sandragrauschopf avatar soniacasas avatar stassl avatar vadimeisenbergibm avatar winklerrr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-style-guide's Issues

#ed function params

Using #name to set both the external and internal names of func params seems very handy to me. This shouldforce one not to use unclear names like x, y, etc

Should we recommend this syntax and make a special mention of it? It does make thecode shorter ... For example:

Func a(myExternalname myInternalparamName:Int)

Vs

Func a(#myParamName:Int)

Spelling courtesy of iphone

Accessing self in let issue

While defining property via let one has no access to other swift class members, so example from style guide would not work:
let width = 120.0 //Double
let widthString = (width as NSNumber).stringValue //String

Spacing Screenshot

Because it would be lengthy to describe where to make the changes and what changes precisely make, this is a screenshot that can be used to show the indentation preferences.
Screenshot of indentation preferences xcode

How to refer to Optional and unwrapped types

Obviously when referring to an Optional type that's important because the user needs to unwrap it before using, e.g.:

The function blahblah(param:) is great for the given purpose. The param parameter is of type Int? and controls blah.

But how should we refer to unwrapped types? How about if the param parameter was of type Int! eg. we can for :

  1. The function blahblah(param:) is great for the given purpose. The param parameter is of type Int and controls blah.

or something like that:

  1. The function blahblah(param:) is great for the given purpose and take a single Int parameter.

Eg. discussion is: unwrapped type can be used directly, so we can just omit the "!", or contra- argument would be: if there's bad programming the param can be nil and crash the app, so it's best if the reader is explicitly told that the type is "Int!"

I myself tend to side with leaving the "!" out, but maybe there are strong arguments the other way?

Please provide draft document and then ask for review

This process is being run inefficiently. We are debating issues that probably don't need it. In many of these cases, we are simply asking "should we use old Obj-C syntax or new Swift syntax?"

Could whomever is in charge of this please write a draft proposal of this document and then open it up to discussion? In many cases, we might just agree to what is there and not have to bother with back and forth that we all know is probably going to end with "do it like Swift".

I don't mean this as a complaint, I just believe that design by committee is a bad idea and we'd probably find more agreement if we had a doc to start with.

Class prefixes

Because you get an automatic namespace that is named after your project, I vote that we drop the requirement of having an RWT / SKT / whatever prefix for class names and global constants.

If there is a naming conflict with a built-in symbol, you can always prefix with the name of the framework (or your project) to disambiguate.

Silly example:

class UIButton { ... }   // this is now allowed (but not a good idea)
let myButton1 = UIButton(...)
let myButton2 = UIKit.UIButton(...)   // get the one from UIKit
let whatever = Swift.Array()

unwrapping optionals

When you access an optional, you need to check it first. There are two ways to do this:

if someOptional {
  someOptional?.someFunc()
}

or

if let s = someOptional {
  s.someFunc()
}

Preferences? Reasons to use one over the other? Exceptions to those rules?

Discussion: Singletons?

What should be the appropriate syntax for declaring singletons in Swift? Should we still use dispatch_once or does a global constant variable suffice? Both official books on Swift don't even include the word "singleton", so we're not getting much guidance from Apple here.

Classes and Structures property and constant ordering

The section on classes and structures recommends that variable and constants listed first. I think this makes sense when those things are part of the public API. However, I can imagine many cases in which the properties are an implementation detail. In this case you want to hide it away with the rest of the private methods.

As an example, suppose you are implementing a Set class, and version 1.0 implements it in terms of a native swift Dictionary. It would be great if you could completely hide it away from the user. Listing it first doesn't really help.

Title case usage for let values

let MaximumWidgetCount = 100

I hate to say it, but I vehemently believe that TitleCase should be used strictly for names of types, and never for instances of types.

It's a difficult thing to get used to, coming from the worlds of I_AM_REALLY_SURE_I_WANT_THIS_TO_BE_A_CONSTANT of Java and kIWantToSignifyThisIsAConstantButHateCaps of Objective-C.

I'd argue that the ubiquity of "make it a let until proven otherwise" in Swift is very beneficial to readability as well as the compiler's ability to better optimize code (due to the increased frequency of immutable values), and that this ubiquity means that title case is not necessary, even for class-level constants.

:]

Nested Types

Definitely a new feature for us. What are some do's/dont's that we should consider?

I really like the example used in "the book".

struct BlackjackCard {

    enum Suit: Character {
        // ...
    }

    enum Rank: Int {
        // ...
    }

    let rank: Rank, suit: Suit
    var description: String {
        // ...
    }
}

I love the idea of using nested "private" types to create container classes. Could we use nested types as a means to namespace library/framework classes?

Priorities on sections

Move the Language section below Smileys. I realize it might not be in order of importance, but still, color vs. colour as the first item? Noooope

In general the sections should be prioritized

Closure vs closure expression

I read this the other day: http://airspeedvelocity.net/2014/06/16/closures-and-closure-expressions-are-two-different-things/

I think it's good to use proper terminology in our style guide. A closure is something that captures from its environment. This can be a named function or it can be an anonymous inline function, aka a closure expression, defined with just { }.

In other words, just because you use { } to define a block of code doesn't necessarily make it a closure.

Enum options format

Which one is prefered?

  1. CamelCase with first capitalised letter

enum Code: Int { case HttpResponseMissingParam = -2 }

  1. CamelCase

enum Code: Int { case httpResponseMissingParam = -2 }

Appending to arrays

Is there a consensus on use of operators instead of methods when possible?
The Swift Programming Language shows that the addition operator += can be used instead of the append method to add to an array.

Considering the preference for subscript syntax, should use of the += be preferred to keep code concise?

Implicitly unwrapped variables (varName!)

It seems to me that implicitly unwrapped variables are there mostly to bridge from ObjC, since they behave almost identically to ObjC variables.

In pure Swift code using Optionals or regular variables should be enough. The only case where an implicitly unwrapped variable is needed is for IBOutlet, but I believe if you attach IBOutlet the variable is inferred to be implicitly unwrapped.

However, implicitly unwrapped variables do make the code easier to read since you can get away without using optional binding at times.

Personally I'm leaning towards no declaring variables with varName! at all and embrace Optionals and optional binding/chaining where needed.

MARK missing end dash

You kinda sorta implemented my MARK suggestion. For the ones that go above an extension, I think it's important to have the trailing - as well. If you just do a leading dash, it really looks no different than a comment in the main class, and is hard to read. Having the trailing dash adds that trailing line, and really calls it out as a separate section in the drop-down.

Did you intentionally leave it out?

Spaces after colons or not

Are we going to put spaces after the colons or not? In Obj-C we don't, in the Swift book they do.

var something = AwesomeClass(param: value, otherParam: otherValue)

versus:

var something = AwesomeClass(param:value, otherParam:otherValue)

Also for the declaration of variables:

var something: String
var something:String
var something : String

And classes:

class MyClass: SuperClass
class MyClass : SuperClass

My vote is to do it like the Swift book, colon space.

Control structures and Blocks are indistinguishable.

It's only a month old, and it's not C. Let's get away from archaic formatting and adopt control structures open brackets on a new line.

Otherwise reading quickly through code it's hard to distinguish a conditional from a block param:

if something {
    \\ code
}

something {
    \\ code
}

whereas, if control structures always had open brackets on the new line, there would be far less oversight when reading:

if something
{
    \\ code
}

something {
    \\ code
}

And furthermore, if you can agree with that, why not just adopt bracket on a new line all around, it makes things much more readable:

class Foo
{
    \\ code
}

Discussion: Type inference

This is going to be a fun one! As I a sure you are all aware, you leave off the type for a variable or a constant when it is possible for the compiler to infer it from the context.

The big 'pro' of this is more compact code (especially if the type is something funky like (String, Bool[]) -> () or uses nested generics, but the con is that it can make the code harder to read, for example var foo = something(), what type is foo? you have to look at the something function to find out.

My feeling is that using type inference everywhere is a mistake, it should only be used when it is obvious to the developer as well as the compiler exactly what the type is, or if the introduction of the type itself makes the code harder to read.

Preferred:

var foo = 23
var complexType = soSomethingClever()

Not Preferred:

var foo: Int = 23 // too obvious!
var complexType: Dictionary<Int,Array<String>> = soSomethingClever() // too complicated!

Categorize the style guide items better

I'd like to group the items better. e.g. Type inference and type choice in a top-level "Types"; Semicolons and Spacing in "Syntax", etc. "Classes and Structures" could be its own h2 with several h3 sections inside.

Preference between Array<Type> vs Type[]

This doesn't need to go into the guide, and I'm fine with either one, just wanted to hear some thoughts.

I feel that:

Array<Type> demonstrates that its a generic a tad more.
Type[] is a tad cleaner.

Is there any differences between these two that I might be missing?

Order of declarations in classes and structs

The style guide currently says that public methods come before private methods. I am not a fan of that.

Things that are conceptually related should be close together, so if public method a() uses private methods b() and c(), then b and c should be near to a, not below all other public methods.

Of course, we don't know what sort of access controls will be added to Swift, but my vote is for keeping related methods together even if this means mixing "public" and "private".

Proposal: Use let for all constant values

I find myself using let for constant class properties, but often forget that you can use let for constants within the scope of functions.

My proposal is that let is used for any value that is a constant.

Class structure/organization

Previously with Objective-C, I always used the following patterns:

  • Public methods/properties in the header file
  • Private properties in the implementation file w/ a class extension
  • Private methods just implemented, not declared
  • Separating and grouping methods with #pragma mark (inits, delegate methods, overrides)

Now with Swift, we don't really have the notion of private & public (though on Twitter I've seen it might be in the works?). We also lost the ability to use #pragma mark. We also now have to declare methods with override.

Should we group functions with comments, like this?

Closures

Closures

return SKAction.customActionWithDuration(effect.duration) { 
  node, elapsedTime in 
  // more code goes here
}
attendeeList.sort { 
  a, b in
  a > b
}

How do you think?

Misleading class structure section

The class structure define private and public methods.
I find this misleading since the current version of swift doesn't support private methods.

Organize classes and structures (i.e. types defined using struct) in the following order:

variable and constant properties
initializers
public methods
private methods

Using self

While writing Swift code, I catch myself typing self.propertyName and self.method() a lot. But in Swift (as in C++, C# and Java) using self is not necessary unless you're trying to resolve an ambiguous situation.

I suggest we don't use self except for that purpose.

Golden Path

To steal from our Objective-C style guide, I propose the inclusion of the Golden Path rule in this guide:

Golden Path

When coding with conditionals, the left hand margin of the code should be the "golden" or "happy" path. That is, don't nest if statements. Multiple return statements are OK.

Preferred:

func someMethod() {

  if someBoolValue == false {
    return
  }

  // Do something important
}

Not Preferred:

func someMethod() {

  if someBoolValue == true {
    // Do something important
  }
}

How to name functions when you're writing about them

I just updated my Candy Crush tutorial to Swift and found that referencing function names from the text can be awkward.

For example, I have the method:

func convertPointFromColumn(column: Int, row: Int) -> CGPoint

This uses the style where the first argument is named as part of the function name.

So in the text, should I refer to this as:

  • convertPointFromColumn()
  • convertPointFromColumn(row:)
  • convertPointFromColumn(column:, row:)

The first one is the shortest but also incomplete because row: is part of the function name.

The second one might be misleading because a reader may think row: is the argument, not part of the name.

The third one is the most correct, but also the longest and "noisiest".

Note that Xcode calls this method convertPointFromColumn(_, row:). That's also an option but not a very nice one...

Preferred for-loop type

As different people may have different preferences, I think that a standard for-loop type across all the site's materials would be best, instead of having different types used in different places. For example, both these are the same:

for var i = 0; i < 10; ++i{
    println(i)
}

for j in 0..10{
    println(j)
}

The second seems to be the preferred loop by Apple, and has several benefits:

  • Not as long (for books this is helpful)
  • Easier to look at (the var, semicolons, and math characters are gone)
  • Easier to understand quickly (in my opinion, less clutter than the first– might be just me)
  • Can take ranges created by .. and ... (very convenient)
  • Can use an underscore if the value is not needed

There are likely circumstances that the first would need (or want) to be used, but generally, I feel this new Swift for-loop syntax is the style we should adopt.

Nothing says that we need to standardize the for-loop syntax. I think doing so would help to make the code more consistent.

Just to keep track, certain cases where the first solution still is needed:

  • counting backwards (no 10..0)
  • counting by 2's (or other integers)
  • floats

I'll try keeping this updated when new cases come to mind.

Swift native types vs. ObjC native types

Is there any preference to use native Swift type vs. ObjC type?
Not sure if there are any side effects or benefits, so I thought I would pose this as a new issue.

For example both of the following declarations are valid:

@objc class LoggedDate {
    let date: NSDate
    let formattedDateAsString: NSString
    init(date: NSDate, formattedDateAsString: NSString) {
        self.date = date
        self.formattedDateAsString = formattedDateAsString
    }
}

and

@objc class LoggedDate {
    let date: NSDate
    let formattedDateAsString: String
    init(date: NSDate, formattedDateAsString: String) {
        self.date = date
        self.formattedDateAsString = formattedDateAsString
    }
}

and formattedDateAsString can be assigned to an ObjC property that is NSString, e.g. cell.textLabel.text = loggedDate.formattedDateAsString in a Swift class.

We can extend this question to cover
Int vs. NSInteger or
Float vs. float and CGFloat, or
var arrayOfInt = [1, 2, 3] vs. var arrayOfInt = NSArray(objects: 1, 2, 3)

Naming of boolean variables

As far as I know, you can't name setters and getters differently in Swift. Objective C prefixes getters for boolean properties with "is" (so a property named "visible" would have a setter setVisible, a getter isVisible and a backing variable called _visible).

Is there some consensus on how to name booleans in Swift? One could of course create a separate computed variable prefixed with "is" to access a property, but I think that would be overkill. "is" or no "is", what do you prefer (and why)?

Getter/Setter Formatting

For some reason, Apple decided not to indent the getter/setter definitions in their example code, it looks like this:

struct AlternativeRect {
    var origin = Point()
    var size = Size()
    var center: Point {
    get {
        let centerX = origin.x + (size.width / 2)
        let centerY = origin.y + (size.height / 2)
        return Point(x: centerX, y: centerY)
    }
    set {
        origin.x = newValue.x - (size.width / 2)
        origin.y = newValue.y - (size.height / 2)
    }
    }
}

I think that's quite ugly and maybe we should just do normal indentation:

struct AlternativeRect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set {
            origin.x = newValue.x - (size.width / 2)
            origin.y = newValue.y - (size.height / 2)
        }
    }
}

Of course, with 2 spaces instead of 4 :]. Any thoughts?

Method Access Modifiers

I realized that Swift does not make any necessary order to the modifiers before methods.

public override func shouldAutorotate() -> Bool
or
override public func shouldAutorotate() -> Bool
both work the same way. It probably applies to other modifiers also.

I think that the public/private/internal should come first, but it is not yet specified in the style guide because access modifiers are new to Swift.

Variable shadowing can lead to harder-to-read code.

I think we should reconsider our position on using shadow variables when unwrapping. Our current argument is that the compiler will correct you if you try to use the wrong variable. I think there's a fundamental flaw in that argument that we've overlooked: It makes code significantly harder to read when not actually being compiled.

I see three major places where reading code like this outside of a compiler causes problems:

  1. Swift beginners. It's very confusing for two things with the same name to have such fundamentally different behavior. This is particularly true for those of us coming from Objective-C, where trying to define two things with the same name causes a compiler warning.
  2. Code reviews. For anyone who has to look through code before it gets merged down, there's an extra level of scrutiny required to make sure "wait, is this person trying to assign the optional or the unwrapped value?"
  3. Book editing. Are we expecting all of our book editors to take not just the sample code but any code typed in the book whatsoever and ensure that it compiles?

Take this example:

func createNewPerson(name: String?) -> Person {
  let person = Person()
  if let name = name {
    person.name = name
  }
 return person
}

Without compiling that code, how do I know that the name variable being set is the unwrapped one rather than the passed-in optional?

This is what I've been doing in my Swift code in a similar situation:

func createNewPerson(name: String?) -> Person {
  let person = Person()
  if let unwrappedName = name {
    person.name = unwrappedName
  }
 return person
}

For me, simply adding unwrapped to the unwrapped variable name makes the flow of the code significantly clearer. We don't have to use that exact syntax (especially since it makes variable names so much longer), but I do think we should reconsider shadowing variables for this reason.

OK, now that I've made my case: FIGHT FIGHT FIGHT FIGHT FIGHT!

1tpffru

What to do about CGFloat

CGFloat is now a distinct floating-point type

I'm not sure if I like or dislike this change. In the Objective-C world, it was common to use CGFloat as the default floating-point type and just let the compiler decide its bit size as we did with int when either precision would be "good enough".

What are the opinions of the group? Should we encourage using CGFloat? Or Double? Or just use the type to match whichever API you're using?

Sprite Kit folks especially, if you could weigh in here that would be great.

Carriage Return before func return type?

So this is kind of out there, I am on the fence about it, more so about not doing it but I thought I'd pose the question.

In Swift class readability/scan-ability suffers in that return types are all the way at the end of the function declaration.

Consider the following class, and quickly "scan" the functions for their return types, kind of a pain, right?

class Foo {
    func firstFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject) -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func secondFunction(param1: AnyObject) -> String {
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func thirdFunction(param1: AnyObject, param2: AnyObject) -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func fourthFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject, param4: AnyObject) -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation

        return "foo";
    }

    func fifthFunction(param1: AnyObject, param2: AnyObject) -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func sixthFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject, param4: AnyObject, param5: AnyObject) -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //

        return "foo";
    }
}

Now consider this format...

class Foo {
    func firstFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject)
        -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func secondFunction(param1: AnyObject)
        -> String {
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func thirdFunction(param1: AnyObject, param2: AnyObject)
        -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func fourthFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject, param4: AnyObject)
        -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation

        return "foo";
    }

    func fifthFunction(param1: AnyObject, param2: AnyObject)
        -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func sixthFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject, param4: AnyObject, param5: AnyObject)
        -> String {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //

        return "foo";
    }
}

A little nicer? I think it's easier to read the class at a glance, but at the same time I think it's kind of ugly.

Or a variant where you also give the opening brace its own line as well...

class Foo {
    func firstFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject)
        -> String
    {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func secondFunction(param1: AnyObject)
        -> String
    {
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func thirdFunction(param1: AnyObject, param2: AnyObject)
        -> String
    {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func fourthFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject, param4: AnyObject)
        -> String
    {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation

        return "foo";
    }

    func fifthFunction(param1: AnyObject, param2: AnyObject)
        -> String
    {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //
        //    implementation
        //    implementation
        //    implementationimplementationimplementation
        //    implementationimplementation
        //    implementationimplementationimplementation
        //    implementationimplementationimplementation

        return "foo";
    }

    func sixthFunction(param1: AnyObject, param2: AnyObject, param3: AnyObject, param4: AnyObject, param5: AnyObject)
        -> String
    {
        //    implementation
        //    implementationimplementationimplementation
        //
        //    implementation
        //    implementationimplementationimplementationimplementationimplementation
        //    implementation
        //

        return "foo";
    }
}

Discuss!

Variable name

I was just seeing a video in wwdc 2014 and saw a weird variable name, check the image.

screen shot 2015-01-09 at 10 15 57 am

So they want to use _ instead of camel case for variables?

Discussion: Closure syntax

The Swift closure syntax is incredibly flexible. These are all semantically the same thing:

str.sort({(one: String, two: String) -> Bool in return one.compare(two) < 0})
str.sort({(one, two) in return one.compare(two) < 0})  // return type inferred
str.sort({one, two in return one.compare(two) < 0})  // no need for brackets
str.sort({$0.compare($1) < 0})  // shorthand variable and implicit return
str.sort() {$0.compare($1) < 0}  // sort has a single parameter, so closure can pop outside
str.sort {$0.compare($1) < 0}  // no need for brackets
str.sort(>) // ok, not a closure, but > has the correct signature. Awesome!

Should we recommend that people use the shortest form possible unless it seriously impacts readability?

Discussion: suppressing external names for initialisers

Personally I really dislike the way that all parameters names for initialisers are external by default, e.g.:

struct BoardLocation {
  init(row: Int,column: Int) {
    ...
  }
}

let location = BoardLocation(row: 2, column: 3)

These can be suppressed with an underscore as follows:

struct BoardLocation {
  init(_ row: Int,_ column: Int) {
    ...
  }
}

let location = BoardLocation(2, 3)

What are people's thoughts on this? Personally i like it.

Spacing around control structures

I think it would be a good idea to change the guide slightly around spacing. I think it is better to always have the conditional more closely associated with the code that it controls than any other code around it. This would leave an if / else if / else statement like this:

if user.name == "Drewag" {
    // Do something
}
else if user.name == "other" {
    // Do something else
}
else {
     // Do something else still
}

Following the same logic, a do-while would look like this:

do {
    // Do Something
} while(user.isHappy)

@objc not working as explained.

In the example
@objc (RWTChicken) class Chicken {
The Objective-C header will be created like

SWIFT_CLASS("RWTChicken")
@interface Chicken

So in Objective-C I still have to reference the class as Chicken. Is RWTChicken the intended result?

"Naming" Style

The objective-c guide contained a section on naming. Notably, it pointed out full, descriptive names.

I don't see any reason to change this for swift. Well... except for the fact that the Swift playground opens with the line:

var str = "Hello, playground"

Thoughts?


Long, descriptive method and variable names are good.

Preferred:

`UIButton *settingsButton;
var settingsButton = UIButton()

Not Preferred:

`UIButton *setBut;
var settingsButton = UIButton()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.