Guidelines for iOS development in use at Spotify

Overview

Spotify Objective-C Coding Style

Version: 0.9.0

Our general coding conventions at Spotify are documented on an internal wiki, but specifics for Objective-C and Objective-C++ code in the iOS client are documented here.

License

Copyright (c) 2015-2016 Spotify AB.

This work is licensed under a Creative Commons Attribution 4.0 International License.

Table of Contents

  1. Spacing, Lines and Formatting
  2. Brackets
  3. Naming
  4. Comments
  5. Pragma Marks
  6. Constants
  7. Return Early
  8. Initializers
  9. Headers
  10. Nullability
  11. Strings
  12. Dot Notation
  13. Categories

Spacing, Lines and Formatting

Line length

  • Keep your lines within 120 characters width when possible.
    • In Xcode, you can set a page guide in Text Editing in Preferences.

Whitespace

  • Use 4 spaces for indentation and alignment. Do not use tabs.
  • Trailing whitespace is acceptable only on blank lines, but discouraged even there.
    • In Xcode, select "Automatically trim whitespace" and "Including whitespace-only lines" in Text Editing preferences to handle this automatically.
  • Put spaces after commas, and before and after operators.
  • Do not put spaces between parentheses and what they are enclosing.

Example:

foo("bar") 

Not:

foo( "bar" )

Containers

  • Array one-liners are acceptable unless they have too many items or their values are too long.
NSArray *array = @[@"uno", @"dos", @"tres", @"cuatro"];
  • In that case, break them in several lines:
NSArray *array = @[
    @"This is how we do, yeah, chilling, laid back",
    @"Straight stuntin’ yeah we do it like that",
    @"This is how we do, do do do do, this is how we do",
];
  • Dictionary one-liners are reserved for single pairs only:
NSDictionary *dict = @{@"key" : @"highway"};
  • Format it pretty otherwise, leaving a trailing comma after the last item:
NSDictionary *dict = @{
    @"key1" : @"highway",
    @"key2" : @"heart",
};

Brackets

  • Always use brackets for if / for / while / do-while statements. Even if its a one-liner:
if (itsMagic) {
    [self makeItEverlasting];
}
  • Write follow up else clauses after the previous closing bracket on the same line.
if (hasClue) {
    knowExactlyWhatToDo();
} else if (seeItAllSoClear) {
    writeItDown();
} else {
    sing();
    dance();
}

Naming

Comments

  • Use the // style for single line comments or when appending comments in the same line of code.
  • Use the /* */ style for multi-line comments.

Example:

/*
 This is a multi-line comment. The opening and closing markers are on their
 own lines.

 This is a new paragraph in the same block comment.
 */

stop(); // Hammer-time!

// this is a very brief comment.
  • Document all methods and properties in the headers using Xcode’s documentation style (which is /// at the time of writing). You can select a property or method and use Option+Cmd+/ to generate the documentation template for it. Make sure to use the available markup tags like @param, @return, etc. (these will be auto-generated for you by Xcode).

Pragma Marks

  • Use the pre-processor instruction #pragma mark to mark related groups of methods.

Constants

  • Do not define constants using #define.
  • Publicly (or privately) exposed variables should be constant (trying to assign values will result in compilation error).
extern NSString * const SPTCodeStandardErrorDomain;

Return Early

  • Return early on errors and failed pre-conditions to avoid unnecessary nested brackets and / or unnecessary computations.

Example:

- (void)setFireToTheRain:(id)rain
{
    if ([_rain isEqualTo:rain]) {
        return;
    }

    _rain = rain;
}

Initializers

Example:

- (instancetype)init 
{
    self = [super init];
 
    if (self) {
        // initialize instance variables here
    }
 
    return self;
}

Headers

  • The use of prefix headers has been deprecated. Do not add new code to an existing prefix header.
  • When importing a module use the hash-import variant instead of at-import.
    • Yes: #import <Foundation/Foundation.h>
    • No: @import Foundation;

Nullability

  • Use NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END in header files, and explicitly add nullable when needed. Example:
#import <Foundation/Foundation.h>

@protocol SPTPlaylist;

NS_ASSUME_NONNULL_BEGIN

typedef void(^SPTSomeBlock)(NSData * _Nullable data, NSError * _Nullable error);

@interface SPTYourClass : NSObject

@property (nonatomic, copy, readonly, nullable) NSString *customTitle;
@property (nonatomic, strong, readonly) id<SPTPlaylist> playlist;

- (nullable instancetype)initWithPlaylist:(id<SPTPlaylist>)playlist
                              customTitle:(nullable NSString *)customTitle;

@end

NS_ASSUME_NONNULL_END

Strings

  • All strings presented to the user should be localized.

Dot Notation

  • Use bracket notation when calling non-accessor methods:
[self doSomething];
  • Use bracket notation when accessing globals through a class method:
[MyClass sharedInstance];
  • Set and access properties using dot notation:
self.myString = @"A string";
  • Except in the init or dealloc methods, always use the ivar directly there:
_myString = nil;

Categories

  • Methods in categories on non-Spotify classes must be prefixed spt_ to avoid name clashes.
You might also like...
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)

Perfect: Server-Side Swift 简体中文 Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)

Perfect: Server-Side Swift 简体中文 Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)

Perfect: Server-Side Swift 简体中文 Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

Full featured Spotify iOS Client written in Swift 5
Full featured Spotify iOS Client written in Swift 5

Spotify Client (iOS - Swift 5 - 2021) Full featured Spotify like app written in Swift 5 with MVVM architecture. Features Official Spotify API Use Play

The HTTP library used by the Spotify iOS client
The HTTP library used by the Spotify iOS client

Authentication and back-off logic is a pain, let's do it once and forget about it! This is a library that allows you to centralise this logic and forg

Spotify SDK for iOS
Spotify SDK for iOS

Spotify iOS SDK Overview The Spotify iOS framework allows your application to interact with the Spotify app running in the background on a user's devi

An Elegant Spotify Web API Library Written in Swift for iOS and macOS
An Elegant Spotify Web API Library Written in Swift for iOS and macOS

Written in Swift 4.2 Spartan is a lightweight, elegant, and easy to use Spotify Web API wrapper library for iOS and macOS written in Swift 3. Under th

iOS application to rate songs in Spotify playlists
iOS application to rate songs in Spotify playlists

Description Reviewery is an iOS application to rate songs in Spotify playlists. It's a hobby project built in React Native. Read more in my Medium art

RHPreviewCell - I envied so much Spotify iOS app this great playlist preview cell 😍
RHPreviewCell - I envied so much Spotify iOS app this great playlist preview cell 😍

I envied so much Spotify iOS app this great playlist preview cell 😍, I decided to create my own one 🌶. Now you can give your users ability to quick check what content is hidden under your UITableViewCell. Great think is that this Library not requires 3D Touch support from user device💥.

SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API.
SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API.

SpotifyLogin SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API. Usage of this framework is bound under the Developer Terms o

A paging menu controller built from other view controllers placed inside a scroll view (like Spotify, Windows Phone, Instagram)
A paging menu controller built from other view controllers placed inside a scroll view (like Spotify, Windows Phone, Instagram)

Unfortunately, life gets in the way sometimes and I won't be able to maintain this library any longer and upgrade this library to where it needs to be

a simple macOS menu bar application that shows you the lyrics of current playing spotify track.

lyricsify a simple macOS menu bar application that shows you the lyrics of current playing spotify track.

A real-time, votable, democratized music queue on iPad and iPhone using Spotify
A real-time, votable, democratized music queue on iPad and iPhone using Spotify

Queue'd Music Queue'd is the best way to enjoy music with your friends. Add your favorite songs to a shared music queue at your favorite bars, restaur

A tiny menu bar app detecting the chords of the songs you are listening on iTunes or Spotify.
A tiny menu bar app detecting the chords of the songs you are listening on iTunes or Spotify.

ChordDetector A tiny menu bar app that listens iTunes and Spotify to detect chords of songs! Demo Features iTunes and Spotify support. Saves up to 20

macOS app that allows the control of Spotify and AppleMusic/iTunes music playback from the menu bar.
macOS app that allows the control of Spotify and AppleMusic/iTunes music playback from the menu bar.

PlayStatus is a simple macOS app that allows the control of Spotify, Apple Music(macOS 10.15+) and iTunes including iTunes Radio/Beats1 playback from

A simple Spotify lyrics viewer menu bar app for macOS in Swift 3
A simple Spotify lyrics viewer menu bar app for macOS in Swift 3

lyricsify This is a simple macOS menu bar application that shows you the lyrics of current playing spotify track. All the lyricses are from Wikia webs

Dead-simple queue-oriented client for Spotify
Dead-simple queue-oriented client for Spotify

Spotiqueue A terribly simple macOS app for keyboard-based, queue-oriented Spotify use. Many years ago i built a version which relied on a now-deprecat

Swift framework for authenticating with the Spotify API
Swift framework for authenticating with the Spotify API

SpotifyLogin SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API. Usage of this framework is bound under the Developer Terms o

A pure Swift Spotify Music App in Apple Music style
A pure Swift Spotify Music App in Apple Music style

HBMusic A pure Swift Spotify Music App in Apple Music style. How to run pod inst

Comments
  • Change style of initializer to 'Apple's typical init'

    Change style of initializer to 'Apple's typical init'

    Our previous initiailzer style prevented us from reaching 100% coverage on our unit tests and it would raise issues on static analysis due to nullability in Obj-C.

    opened by ChocoChipset 5
  • Add nullability section and some minor fixes

    Add nullability section and some minor fixes

    • Adds a section on nullability.
    • Adds bullet point on importing headers (use #import instead of @import).
    • Fixes naming of the example method in the return early section. It wasn’t conforming to the guidelines.
    • Bumps copyright year, 2016 :sunglasses:

    @spotify/objc-dev

    opened by rastersize 4
  • Fix broken headings in Markdown files

    Fix broken headings in Markdown files

    GitHub changed the way Markdown headings are parsed, so this change fixes it.

    See bryant1410/readmesfix for more information.

    Tackles bryant1410/readmesfix#1

    opened by bryant1410 2
  • Update to use updated documentation style.

    Update to use updated documentation style.

    Use this form:

    /**
     Sets an action for a given type
     @param action The block containing the action to perform
     @param type The type denoting when to perform that actions
     */
    

    instead of this:

    /**
     * Sets an action for a given type
     * @param action The block containing the action to perform
     * @param type The type denoting when to perform that actions
     */
    
    opened by cerihughes 0
Owner
Spotify
Spotify
GenericTableViewController - An example to use of generics with UITableViewController

GenericTableView An example to use of generics with UITableViewController. With

Gagan Vishal Mishra 1 Mar 21, 2022
This repository contains 🎨 My Xcode theme that I use. It is compatible with all versions of Xcode.

DRL Xcodetheme Installation Automatic (via script) ./install.sh which will install the file in Xcode FontAndColorThemes directory. Restart Xcode Go t

durul dalkanat 19 Oct 21, 2022
An ambient light accessibility framework for iOS.

Ambience Brightness aware accessibility theme switching without coding. Special thanks I'd like to thank Meng To and Marcos Griselli and all the Desig

Tiago Mergulhão 454 Sep 14, 2022
🎨 Powerful theme/skin manager for iOS 9+ 主题/换肤, 暗色模式

Introduction - Demos - Installation - Documents - FAQ - Contribution - 中文文档 Screenshot Running:open SwiftTheme.xcworkspace, run target PlistDemo Intro

Gesen 2.4k Jan 1, 2023
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.

SpotifyClone An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and

null 104 Jan 7, 2023
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.

SpotifyClone An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and

Gabriel Denoni 11 Dec 27, 2021
Disk is a powerful and simple file management library built with Apple's iOS Data Storage Guidelines in mind

Disk is a powerful and simple file management library built with Apple's iOS Data Storage Guidelines in mind

Saoud Rizwan 3k Jan 3, 2023
Apple TextField created according to the Material.IO guidelines of 2019. Featured at Medium.

CocoaTextField Highly customizable text field created according to Material.IO guidelines. Minimum iOS version 11.0 Carthage github "edgar-zigis/Cocoa

Edgar Žigis 266 Nov 26, 2022
Appstore-Review-Guidelines - A curated list of guideline which has to be taken care before submitting your application to Appstore.

Appstore Review Guidelines The App Review Guidelines provide rules and examples across a range of topics, including user interface design, functionali

Aashish Tamsya 14 Dec 16, 2022