├── BEST_PRACTICES.md ├── COMPONENTS.md ├── HYPER_RECIPES.md ├── LICENSE.md ├── PROJECT-STRUCTURE ├── README.md ├── RELEASES.md ├── RESOURCES.md ├── assets ├── code_quality.png ├── xcode-text-settings-objc.png ├── xcode-text-settings-swift.png └── xcode-text-settings.png └── style-guidelines ├── ObjC.md ├── README.md └── Swift.md /BEST_PRACTICES.md: -------------------------------------------------------------------------------- 1 | # Best practices 2 | 3 | ## Table of Contents 4 | 5 | * [Xcode](#xcode) 6 | * [Deployment](#deployment) 7 | * [Comments](#comments) 8 | * [Blocks, delegates or data source](#blocks-delegates-or-data-source) 9 | * [View controllers](#view-controllers) 10 | * [Assets](#assets) 11 | 12 | ## Xcode 13 | 14 | ### Version 15 | 16 | The recommended version of Xcode (and Swift) for all purposes is the current available [in the App Store](https://itunes.apple.com/no/app/xcode/id497799835?mt=12). 17 | 18 | ### Project structure 19 | 20 | The physical files should be kept in sync with the Xcode project files in order to avoid file sprawl. Any Xcode groups created should be reflected by folders in the filesystem. Code should be grouped by type and feature for greater clarity. 21 | 22 | A recommended project structure can be found in [Project Structure](https://github.com/hyperoslo/objective-c-style-guide/blob/master/PROJECT-STRUCTURE). 23 | 24 | ### Warnings 25 | 26 | Enable warnings by adding `-Weverything` to your Build Settings under "Other Compiler Flags". If you need to ignore a specific warning you can use [Clang's pragma feature](http://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas) or add `-Wno-warning-to-be-disabled` (for example `-Wno-gnu-conditional-omitted-operand`). 27 | 28 | ### Plugin compatibility 29 | 30 | After upgrading to a new Xcode version plugins will become disabled until their list of compatible Xcode versions gets updated. In case you can't wait for an official update by the plugins' authors you can try to run [this script](https://gist.github.com/neonichu/9487584/download#). Be sure to find out your Xcode's version UUID first and update it in the script. 31 | 32 | You can get your Xcode version UUID by running 33 | ```shell 34 | /usr/libexec/PlistBuddy -c 'Print DVTPlugInCompatibilityUUID' "$(xcode-select -p)/../Info.plist" 35 | ``` 36 | 37 | 38 | ## Deployment 39 | 40 | ### Semantic Versioning 41 | 42 | We support [semantic versioning](http://semver.org/), and it's important that minor releases are backwards compatible otherwise don't feel shy to make it a major release. 43 | 44 | When making backwards compatible changes, flag your old APIs as deprecated like this: 45 | 46 | ```objc 47 | - (NSInteger)foo:(NSInteger)bar __attribute__((deprecated("Use fooWithBar: instead"))); 48 | ``` 49 | 50 | 51 | ## Comments 52 | 53 | When they are needed, comments should be used to explain **why** a particular piece of code does something. Any comments that are used must be kept up-to-date or deleted. 54 | 55 | Block comments should generally be avoided, as code should be as self-documenting as possible, with only the need for intermittent, few-line explanations. This does not apply to those comments used to generate documentation. 56 | 57 | **Comments style** 58 | 59 | One-line: 60 | ```swift 61 | // Workaround: This is the comment 62 | ``` 63 | 64 | Multiple-lines: 65 | 66 | ```swift 67 | /* 68 | Workaround: This is a comment that spans multiple lines. 69 | Comments should be added when they are not only needed but critical 70 | to understand the underlying block of code. 71 | */ 72 | ``` 73 | 74 | **For example** 75 | 76 | ```objc 77 | - (void)viewWillAppear:(BOOL)animated 78 | { 79 | [super viewWillAppear:animated]; 80 | 81 | /* 82 | Workaround: Selected cell only gets deselected when pressing the back button 83 | dragging the screen to go back doesn't deselect the selected cell. 84 | So, `self.clearsSelectionOnViewWillAppear = YES;` only works sometimes. 85 | */ 86 | NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow]; 87 | if (selectedIndexPath) { 88 | [self.tableView deselectRowAtIndexPath:selectedIndexPath animated:YES]; 89 | } 90 | } 91 | ``` 92 | 93 | 94 | ## Blocks, delegates or data source 95 | 96 | ### Block 97 | - Asynchronous (For example: networking operations) 98 | - User inputs with multiple options (For example: UIAlertView's YES and NO) 99 | - Data source driven inputs (For example: A table items with action blocks that were defined in the data source) 100 | - Returns many values (For example looking for a field in a collection and returning the field and the indexPath) 101 | - If there’s no tracked state or if state it’s defined in the same method 102 | 103 | ### Delegate 104 | - Synchronous (For example: buttons actions in views that should perform on their parents) 105 | - Shouldn't return values 106 | - Provides control over performing an action (For example: UITextField's shouldEndEditing) 107 | - User input with one action (For example: buttons actions in views that should perform on their parents) 108 | - If tracked state is shared (if state is stored in a property or a constant) 109 | 110 | ### Data source 111 | - Returns ONE value 112 | 113 | ## View controllers 114 | 115 | ### Naming 116 | 117 | When naming subclasses of `UIViewController` or friends `UIPageViewController`, `UICollectionViewController`, `UITableViewController`, you don't have to use the `ViewController` suffix. 118 | 119 | For example instead of `HYPRecipesTableViewController` you would do `HYPRecipesController`, this applies for both Objective-C and Swift. 120 | 121 | ### Presenting and dismissing View Controllers 122 | 123 | - It's better practice to call `dismissViewControllerAnimated:completion:` in the `UIViewController` that did the presenting, not in the `UIViewController` that was presented. 124 | 125 | ## Assets 126 | 127 | ### Images 128 | 129 | Image names should be named consistently to preserve organization and developer sanity. They should be named as one [lower camel case](http://c2.com/cgi/wiki?LowerCamelCase) string with a description of their purpose, followed by the un-prefixed name of the class or property they are customizing (if there is one), followed by a further description of color and/or placement, and finally their state. 130 | 131 | **For example:** 132 | 133 | * `refreshBarButtonItem` / `refreshBarButtonItem@2x` and `refreshBarButtonItemSelected` / `refreshBarButtonItemSelected@2x` 134 | * `articleNavigationBarWhite` / `articleNavigationBarWhite@2x` and `articleNavigationBarBlackSelected` / `articleNavigationBarBlackSelected@2x`. 135 | 136 | Images should live in `Images.xcassets`. 137 | -------------------------------------------------------------------------------- /COMPONENTS.md: -------------------------------------------------------------------------------- 1 | Every agnostic component (UI control, category, helper, etc) should be created in a separate repository and in Swift. 2 | 3 | Your component should be unit tested and documented. 4 | 5 | # Steps to create a component 6 | 7 | - [ ] Create repo on GitHub 8 | - [ ] Go to your Projects folder 9 | - [ ] Run `git clone https://github.com/hyperoslo/pod-template ` 10 | - [ ] Run `cd ` 11 | - [ ] Run `./init.rb ` 12 | - [ ] [Enable Travis for your repository](https://travis-ci.org/profile/hyperoslo). If your component doesn't show up press "Sync Now" 13 | - [ ] To test your pod in another project while developing it you have to make sure all changes of your pod are commited and synced, then make sure `pod '', :git => 'https://github.com/hyperoslo/.git` is in the other project's Podfile. Running `pod install ` (first time) or `pod update ` (after each change to your pod) in the other project is required 14 | - [ ] Add your beautiful code and make a `Initial implementation` pull request 15 | - [ ] Publish your pod by running `pod trunk push`(*) 16 | - [ ] Add Hyper as co-owner by running `pod trunk add-owner ios@hyper.no` 17 | - [ ] :cake: 18 | 19 | (*) If you don't have a CocoaPods account you can create one by following [this steps](http://guides.cocoapods.org/making/getting-setup-with-trunk.html#getting-started). 20 | 21 | # Steps to ship your component 22 | 23 | Before shipping your component make sure that the README states what makes your Pod different than the other ones, been made by you might not be enough. It's very important that your README is :star2: fabulous :star2:. 24 | 25 | Make sure to provide a super simple example on how to get your Pod up and running, if it is dependent on other Pods you should explain why you need them and what they do. Don't assume that people know everything. 26 | 27 | If it's a visual component include a `.gif` showing how does it work or what does it do. It helps a lot for people to understand your Pod without having to clone, build and run your project. A good tool to make gifs is [Licecap](http://www.cockos.com/licecap/). 28 | 29 | - [ ] Make sure to have a cool logo, you can ask [@hyperoslo/design](https://github.com/orgs/hyperoslo/teams/design) to give you a hand 30 | - [ ] Submit it to [Cocoa Controls](https://www.cocoacontrols.com/) 31 | - [ ] Make a PR to [iOS Goodies](https://github.com/iOS-Goodies/iOS-Goodies) 32 | - [ ] Submit your component to [Hacker News](https://news.ycombinator.com/), your post should start with **Show HN** 33 | 34 | **Send a few tweets from the @hyperoslo account** 35 | 36 | Always express yourself like you are part of a team, use **"We did this"** and never **"I did this"**. 37 | Take the time to compose personal tweets to all your recipients, copy pasting one message to everyone makes you sound like a robot and feels spammy, don't do this. 38 | 39 | A few examples: 40 | 41 | [@Example](https://twitter.com/hyperoslo/status/585126444331835393), 42 | [@Another example](https://twitter.com/hyperoslo/status/585123729610510339), 43 | [@One more example](https://twitter.com/hyperoslo/status/585123389343424513), 44 | [@Yet another example](https://twitter.com/hyperoslo/status/585120710940557312), 45 | [@Are you still reading examples?](https://twitter.com/hyperoslo/status/585119588075044864) 46 | 47 | - [ ] Send a tweet from the [@hyperoslo](https://twitter.com/hyperoslo) account with a tiny summary and attach the logo of the Pod 48 | - [ ] Send a tweet to [@maniacdev](https://twitter.com/maniacdev) 49 | - [ ] Send a tweet to [@daveverwer](https://twitter.com/daveverwer) and [@iOSDevWeekly](https://twitter.com/iOSDevWeekly) 50 | - [ ] Send a tweet to [@iOSGoodies](https://twitter.com/iOSGoodies) with the link to your PR 51 | - [ ] Send a tweet to [@NatashaTheRobot](https://twitter.com/NatashaTheRobot) 52 | -------------------------------------------------------------------------------- /HYPER_RECIPES.md: -------------------------------------------------------------------------------- 1 | Hi, 2 | 3 | Thanks for your interest in working at Hyper. We are a bunch of passionate developers that enjoy making cool apps and having fun (not necessarily in that order). You'll love it here :) 4 | 5 | Even though you could try and convince us to hire you for your good humor, charm, or cool name, we really care about majestic code. If you have any cool projects in GitHub that you can show us, please send them to us, especially if it's one that you use on a daily basis. But if that's not the case, don't sweat it, we have this cool assignment called Hyper Recipes. 6 | 7 | In [Hyper Recipes](https://github.com/hyperoslo/hyper-recipes), you'll build an application that will present a collection of recipes fetched from our [backend](http://hyper-recipes.herokuapp.com/recipes). Other endpoints [are available](https://github.com/hyperoslo/hyper-recipes/blob/master/README.md) if you are feeling adventurous. You decide the level of complexity, functionality and the look and feel of the application. We appreciate good looking apps and thoughtful user experiences, the App Store is a great source of inspiration. 8 | 9 | We tend to enjoy some popcorn while reviewing your app, reading the code as if it was a fantasy book filled with dragons and unicorns. Please make it shine. 10 | 11 | Also, feel free to use any external libraries you are comfortable with, or keep it vanilla, it's up to you. 12 | 13 | When you are ready to ship, [send us](mailto:ios@hyper.no) the link to your Hyper Recipes repository, and please remember to write concise and understandable commits. 14 | 15 | Thanks, we hope you'll enjoy making some recipes! 16 | 17 | PS: You'll get 10000 additional points if you use our [style guidelines](style-guidelines/README.md). 18 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Licensed under the **MIT** license 2 | 3 | > Copyright (c) 2013 - 2014 The New York Times Company 4 | > 5 | > Copyright (c) 2014 - 2015 Hyper Interaktiv AS 6 | > 7 | > Permission is hereby granted, free of charge, to any person obtaining 8 | > a copy of this software and associated documentation files (the 9 | > "Software"), to deal in the Software without restriction, including 10 | > without limitation the rights to use, copy, modify, merge, publish, 11 | > distribute, sublicense, and/or sell copies of the Software, and to 12 | > permit persons to whom the Software is furnished to do so, subject to 13 | > the following conditions: 14 | > 15 | > The above copyright notice and this permission notice shall be 16 | > included in all copies or substantial portions of the Software. 17 | > 18 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 19 | > EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 20 | > MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 21 | > IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | > CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 23 | > TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 24 | > SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 25 | -------------------------------------------------------------------------------- /PROJECT-STRUCTURE: -------------------------------------------------------------------------------- 1 | ProjectName 2 | | 3 | |— Vendor # 3rd party code that doesn't use CocoaPods 4 | |—— METCalendarViewer 5 | |—— LZOPhotoViewer 6 | | 7 | |— Library # Anything that falls outside of the MVC pattern 8 | |—— Views 9 | |—— Networking 10 | |—— Categories 11 | |—— Containers 12 | |—— Base 13 | |—— Managers 14 | |—— Utils (better if can be a category) 15 | | 16 | |— AppDelegate 17 | | 18 | |— Source 19 | |—— Recipes 20 | |——— Views 21 | |——— Controllers 22 | |——— Networking 23 | | 24 | |—— Ingredients 25 | |——— Views 26 | |——— Controllers 27 | |——— Networking 28 | | 29 | |—— Comments 30 | |——— Views 31 | |——— Controllers 32 | |——— Networking 33 | | 34 | |— Models # Human files. Usually generated by Mogenerator 35 | |—— Autogenerated # machine files, generated by Mogenerator 36 | | 37 | |— Tests 38 | |—— Helpers 39 | |—— Models 40 | |—— Controllers 41 | |—— Networking 42 | |—— Resources // Mocked JSON responses 43 | | 44 | |— Resources 45 | |—— Storyboards 46 | |—— Images.xcassets 47 | |—— JSONs 48 | |—— Sounds 49 | |—— Others 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hyper's iOS Playbook 2 | 3 | 4 | Author: Randall Munroe, xkcd.com 5 | 6 | 7 | This is our playbook, there are many like it, but this one is ours. 8 | 9 | Wanna work with us? [We have a fun assigment](https://github.com/hyperoslo/iOS-playbook/blob/master/HYPER_RECIPES.md) that you might be interested in. 10 | 11 | [Email us](mailto:ios@hyper.no) your GitHub repo! 12 | 13 | ------------------------------------------ 14 | 15 | ### Should my guideline be in code style or best practices? 16 | 17 | If your guideline applies to both Swift and Objective-C, then it's probably a best practice. 18 | -------------------------------------------------------------------------------- /RELEASES.md: -------------------------------------------------------------------------------- 1 | # Releases 2 | 3 | Steps for releasing a new version of your app: 4 | 5 | 1. Switch to the `master` branch 6 | 2. Bump the projects version number (make sure to use [semantic versioning](http://semver.org/)) 7 | 3. Create and upload the archive to HockeyApp 8 | 4. Commit and push your changes to the `master` branch 9 | 5. Create a [release on GitHub](https://help.github.com/articles/creating-releases/). If the release uses the `staging` server, mark it as `pre-release` 10 | -------------------------------------------------------------------------------- /RESOURCES.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | 3 | ## The new wave 4 | 5 | iOS, mainly thanks to Swift, is transitioning to a whole new level. Now you hear more about Functional Programming, Reactive Programming, Immutability and so much more: 6 | 7 | - Great introduction by [Andy Matuschak](https://twitter.com/andy_matuschak) about why this concepts are important and how they help to make better software 8 | https://developer.apple.com/videos/wwdc/2014/ 9 | http://realm.io/news/andy-matuschak-controlling-complexity/ 10 | 11 | - Rich Hickey, the author of Clojure, is an independent software designer, consultant and application architect with over 20 years of experience in all facets of software development. 12 | http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey 13 | http://www.infoq.com/presentations/Simple-Made-Easy 14 | 15 | - Haskell and Scala are probably some of the most relevant functional languages out there, learning them is embracing *the new wave* 16 | 17 | - Learn Haskell 18 | http://learnyouahaskell.com/ 19 | 20 | - Principles of Reactive Programming 21 | https://www.coursera.org/course/reactive 22 | 23 | - Mostly Adequate Guide to Functional Programming in Javascript 24 | https://drboolean.gitbooks.io/mostly-adequate-guide/ 25 | 26 | - Dan Grossman’s Programming Languages Course 27 | http://oleb.net/blog/2014/12/programming-languages-mooc/ 28 | 29 | - Functional Programming Principles in Scala 30 | https://www.coursera.org/course/progfun 31 | 32 | - Immutability: It's much easier to deal with 2 immutable things than 1 mutable. You can pass them around and no one can change them. `Immutability = happy programer life` 33 | https://www.youtube.com/watch?v=DK3vO3fUnlo 34 | 35 | -------------------------------------------------------------------------------- /assets/code_quality.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperoslo/iOS-playbook/3ef89ad7a768307b4a13005b80dc89d633781f2b/assets/code_quality.png -------------------------------------------------------------------------------- /assets/xcode-text-settings-objc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperoslo/iOS-playbook/3ef89ad7a768307b4a13005b80dc89d633781f2b/assets/xcode-text-settings-objc.png -------------------------------------------------------------------------------- /assets/xcode-text-settings-swift.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperoslo/iOS-playbook/3ef89ad7a768307b4a13005b80dc89d633781f2b/assets/xcode-text-settings-swift.png -------------------------------------------------------------------------------- /assets/xcode-text-settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperoslo/iOS-playbook/3ef89ad7a768307b4a13005b80dc89d633781f2b/assets/xcode-text-settings.png -------------------------------------------------------------------------------- /style-guidelines/ObjC.md: -------------------------------------------------------------------------------- 1 | # Hyper Objective-C Style Guide 2 | 3 | This style guide outlines the coding conventions of the iOS team at Hyper. 4 | 5 | ## Introduction 6 | 7 | Here are some of the documents from Apple that informed the style guide. If something isn't mentioned here, it's probably covered in great detail in one of these: 8 | 9 | * [The Objective-C Programming Language](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html) 10 | * [Cocoa Fundamentals Guide](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/Introduction/Introduction.html) 11 | * [Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html) 12 | * [iOS App Programming Guide](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/Introduction/Introduction.html) 13 | 14 | ## Table of Contents 15 | 16 | * [Dot-Notation Syntax](#dot-notation-syntax) 17 | * [Spacing](#spacing) 18 | * [Conditionals](#conditionals) 19 | * [Ternary Operator](#ternary-operator) 20 | * [Error handling](#error-handling) 21 | * [Methods](#methods) 22 | * [Variables](#variables) 23 | * [Naming](#naming) 24 | * [Init & Dealloc](#init-and-dealloc) 25 | * [Literals](#literals) 26 | * [CGRect Functions](#cgrect-functions) 27 | * [Constants](#constants) 28 | * [Enumerated Types](#enumerated-types) 29 | * [Private Properties](#private-properties) 30 | * [Booleans](#booleans) 31 | * [Singletons](#singletons) 32 | 33 | ## Dot-Notation Syntax 34 | 35 | Dot-notation should **always** be used for accessing properties. Bracket notation is preferred when using methods and in other instances. 36 | 37 | **For example:** 38 | ```objc 39 | view.backgroundColor = [UIColor orangeColor]; 40 | [UIApplication sharedApplication].delegate; 41 | ``` 42 | 43 | **Not:** 44 | ```objc 45 | [view setBackgroundColor:[UIColor orangeColor]]; 46 | UIApplication.sharedApplication.delegate; 47 | ``` 48 | 49 | ## Spacing 50 | 51 | * Indent using 4 spaces. Never indent with tabs. This should be configured on the project. 52 | 53 | ![Xcode indent settings](https://raw.githubusercontent.com/hyperoslo/iOS-playbook/master/assets/xcode-text-settings-objc.png) 54 | 55 | * `if`/`else`/`switch`/`while` and friends should always open on the same line as the statement, conditions like else or do that follow if or while respectively start in the same line where the previous condition ends. 56 | 57 | **For example:** 58 | ```objc 59 | if (user.isHappy) { 60 | // Do something 61 | } else { 62 | // Do something else 63 | } 64 | ``` 65 | * There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but often there should probably be new methods. 66 | * `@synthesize` and `@dynamic` should each be declared on new lines in the implementation. 67 | 68 | ## Conditionals 69 | 70 | Conditional bodies should have braces, except when initializing and lazy loading. 71 | 72 | #### Common code 73 | 74 | **For example:** 75 | ```objc 76 | if (!error) { 77 | Field *field = [self.collectionView fieldForIndexPath:field]; 78 | return field.isValid; 79 | } 80 | ``` 81 | 82 | **even if it's one line** 83 | 84 | ```objc 85 | if (!error) { 86 | return success; 87 | } 88 | ``` 89 | 90 | **Not:** 91 | ```objc 92 | if (!error) 93 | return success; 94 | ``` 95 | 96 | **Initializer** 97 | 98 | ```objc 99 | - (instancetype)initWithFrame:(CGRect)frame { 100 | self = [super initWithFrame:frame]; 101 | if (!self) return nil; 102 | 103 | return self; 104 | } 105 | ``` 106 | 107 | **Lazy loading** 108 | 109 | ```objc 110 | - (UILabel *)label { 111 | if (_label) return _label; 112 | 113 | _label = [UILabel new]; 114 | 115 | return _label; 116 | } 117 | ``` 118 | 119 | ### Ternary Operator 120 | 121 | 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. 122 | 123 | **For example:** 124 | ```objc 125 | result = (a > b) ? x : y; 126 | ``` 127 | 128 | **Not:** 129 | ```objc 130 | result = a > b ? x = c > d ? c : d : y; 131 | ``` 132 | 133 | ## Error handling 134 | 135 | When methods return an error parameter by reference, switch on the returned value, not the error variable. 136 | 137 | **For example:** 138 | ```objc 139 | NSError *error = nil; 140 | BOOL shouldAcceptCalls = [self trySomethingWithError:&error]; 141 | if (!shouldAcceptCalls) { 142 | // Handle Error 143 | } 144 | ``` 145 | 146 | **Not:** 147 | ```objc 148 | NSError *error = nil; 149 | [self trySomethingWithError:&error]; 150 | if (error) { 151 | // Handle Error 152 | } 153 | ``` 154 | 155 | Some of Apple’s APIs write garbage values to the error parameter (if non-NULL) in successful cases, so switching on the error can cause false negatives (and subsequently crash). 156 | 157 | ## Methods 158 | 159 | In method signatures, there should be a space after the scope (-/+ symbol). There should be a space between the method segments. 160 | 161 | **For Example**: 162 | ```objc 163 | - (void)updatePersonWithName:(NSString *)name 164 | andImage:(UIImage *)image; 165 | ``` 166 | 167 | In the method implementation opening bracket should **always** be placed in the same line as the last parameter: 168 | 169 | **For Example**: 170 | ```objc 171 | - (void)updatePersonWithName:(NSString *)name 172 | andImage:(UIImage *)image { 173 | // Implementation 174 | } 175 | ``` 176 | 177 | In method invocations the parameters should be colon aligned, if the method becomes a cascade consider splitting the logic in several methods. 178 | 179 | **For Example**: 180 | ```objc 181 | [someObject updatePersonWithName:@"Example Text" 182 | image:[UIImage imageNamed:@"Image.png"] 183 | andDescription:@"Example description"]; 184 | ``` 185 | 186 | ## Variables 187 | 188 | Variables should be named as descriptively as possible. Abbreviated variable names should be avoided. 189 | 190 | Asterisks indicating pointers belong with the variable, e.g., `NSString *text` not `NSString* text` or `NSString * text`, except in the case of [constants](https://github.com/hyperoslo/iOS-playbook/blob/master/STYLE_GUIDELINES.md#constants). 191 | 192 | Property definitions should be used in place of naked instance variables whenever possible. Direct instance variable access should be avoided except in initializer methods (`init`, `initWithCoder:`, etc…), `dealloc` methods and within custom setters and getters. For more information on using Accessor Methods in Initializer Methods and dealloc, see [here](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW6). 193 | 194 | When declaring a `strong` property, you can leave out the `strong` keyword as this is the default. 195 | 196 | When declaring properties in public headers that contain mutable counterparts (`NSString`, `NSDictionary`, `NSArray`) make sure to include the `copy` keyword. 197 | 198 | **For example:** 199 | 200 | ```objc 201 | @interface HYPSection: NSObject 202 | 203 | @property (nonatomic) NSString *headline; 204 | 205 | @end 206 | ``` 207 | 208 | **Not:** 209 | 210 | ```objc 211 | @interface HYPSection : NSObject { 212 | NSString *headline; 213 | } 214 | ``` 215 | 216 | ## Naming 217 | 218 | Apple naming conventions should be adhered to wherever possible, especially those related to [memory management rules](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html) ([NARC](http://stackoverflow.com/a/2865194/340508)). 219 | 220 | Long, descriptive method and variable names are good. 221 | 222 | **For example:** 223 | 224 | ```objc 225 | UIButton *settingsButton; 226 | ``` 227 | 228 | **Not** 229 | 230 | ```objc 231 | UIButton *setBut; 232 | ``` 233 | 234 | A three letter prefix (e.g. `HYP`) should always be used for class names and constants, however may be omitted for Core Data entity names. Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity. 235 | 236 | **For example:** 237 | 238 | ```objc 239 | static const NSTimeInterval HYPArticleViewControllerNavigationFadeAnimationDuration = 0.3; 240 | ``` 241 | 242 | **Not:** 243 | 244 | ```objc 245 | static const NSTimeInterval fadetime = 1.7; 246 | ``` 247 | 248 | Properties and local variables should be camel-case with the leading word being lowercase. 249 | 250 | Instance variables should be camel-case with the leading word being lowercase, and should be prefixed with an underscore. This is consistent with instance variables synthesized automatically by LLVM. **If LLVM can synthesize the variable automatically, then let it.** 251 | 252 | **For example:** 253 | 254 | ```objc 255 | @synthesize descriptiveVariableName = _descriptiveVariableName; 256 | ``` 257 | 258 | **Not:** 259 | 260 | ```objc 261 | id varnm; 262 | ``` 263 | 264 | Prefer `remoteID` or `localID` when naming local or remote foreign keys. 265 | 266 | **For example:** 267 | 268 | ```objc 269 | Note *note; 270 | note.localID = 12; // local 271 | note.remoteID = 10; // from backend 272 | ``` 273 | 274 | **Not:** 275 | 276 | ```objc``` 277 | Note *note; 278 | note.noteID = 1; 279 | ``` 280 | 281 | **or** 282 | 283 | ```objc``` 284 | Note *note; 285 | note.noteId = 1; 286 | ``` 287 | 288 | ## Pragma marks 289 | 290 | Use pragma marks to structure your code. Sort them in a linear fashion, starting with the initialization, lazy loaded properties and other getters followed by the setters. 291 | 292 | Private and custom delegate methods are added at the bottom. 293 | 294 | Methods that overwrite their parent methods should be grouped in `#pragma mark - PARENT_CLASS` 295 | 296 | ```objc 297 | #pragma mark - Initializers 298 | 299 | #pragma mark - Getters 300 | 301 | #pragma mark - Setters 302 | 303 | #pragma mark - View life cycle 304 | 305 | #pragma mark - Actions 306 | 307 | #pragma mark - Notifications 308 | 309 | #pragma mark - HYPBaseTableViewController 310 | 311 | #pragma mark - UITableViewDelegate 312 | 313 | #pragma mark - CustomViewDelegate 314 | 315 | #pragma mark - Private methods 316 | ``` 317 | 318 | ## init and dealloc 319 | 320 | `dealloc` methods should be placed at the top of the implementation, directly after the `@synthesize` and `@dynamic` statements. `init` should be placed directly below the `dealloc` methods of any class. 321 | 322 | `init` methods should be structured like this: 323 | 324 | ```objc 325 | - (instancetype)init { 326 | self = [super init]; // or call the designated initalizer 327 | if (!self) return nil; 328 | 329 | // Custom initialization 330 | 331 | return self; 332 | } 333 | ``` 334 | 335 | ## Literals 336 | 337 | `NSString`, `NSDictionary`, `NSArray`, and `NSNumber` literals should be used whenever creating immutable instances of those objects. Pay special care that `nil` values not be passed into `NSArray` and `NSDictionary` literals, as this will cause a crash. 338 | 339 | **For example:** 340 | 341 | ```objc 342 | NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"]; 343 | NSDictionary *productManagers = @{@"iPhone" : @"Kate", @"iPad" : @"Kamal", @"Mobile Web" : @"Bill"}; 344 | NSNumber *shouldUseLiterals = @YES; 345 | NSNumber *buildingZIPCode = @10018; 346 | ``` 347 | 348 | **Not:** 349 | 350 | ```objc 351 | NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil]; 352 | NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil]; 353 | NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES]; 354 | NSNumber *buildingZIPCode = [NSNumber numberWithInteger:10018]; 355 | ``` 356 | 357 | Literals should be used when accessing `NSDictionary` or `NSArray` instances. 358 | 359 | ```objc 360 | NSString *name = names[0]; 361 | NSString *productManager = productManagers[@"iPhone"]; 362 | ``` 363 | 364 | **Not:** 365 | 366 | ```objc 367 | NSString *name = [names objectAtIndex:0]; 368 | NSString *productManager = [productManagers objectForKey:@"iPhone"]; 369 | ``` 370 | 371 | ## CGRect Functions 372 | 373 | When accessing the `x`, `y`, `width`, or `height` of a `CGRect`, always use the [`CGGeometry` functions](http://developer.apple.com/library/ios/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html) instead of direct struct member access. From Apple's `CGGeometry` reference: 374 | 375 | > All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics. 376 | 377 | **For example:** 378 | 379 | ```objc 380 | CGRect frame = self.view.frame; 381 | 382 | CGFloat x = CGRectGetMinX(frame); 383 | CGFloat y = CGRectGetMinY(frame); 384 | CGFloat width = CGRectGetWidth(frame); 385 | CGFloat height = CGRectGetHeight(frame); 386 | ``` 387 | 388 | **Not:** 389 | 390 | ```objc 391 | CGRect frame = self.view.frame; 392 | 393 | CGFloat x = frame.origin.x; 394 | CGFloat y = frame.origin.y; 395 | CGFloat width = frame.size.width; 396 | CGFloat height = frame.size.height; 397 | ``` 398 | 399 | ## Constants 400 | 401 | Constants are preferred over in-line string literals or numbers, as they allow for easy reproduction of commonly used variables and can be quickly changed without the need for find and replace. Constants should be declared as `static` constants and not `#define`s unless explicitly being used as a macro. 402 | 403 | They should be located in the class that uses them, if they are shared between classes you can have them in the public header. 404 | 405 | **For example:** 406 | 407 | ```objc 408 | static NSString * const HYPAboutViewControllerCompanyName = @"Hyper"; 409 | 410 | static const CGFloat HYPImageThumbnailHeight = 50.0f; 411 | 412 | static const CGSize HYPImageDefaultSize = {40.0f, 40.0f}; 413 | ``` 414 | 415 | **Not:** 416 | 417 | ```objc 418 | #define CompanyName @"Hyper" 419 | 420 | #define thumbnailHeight 2 421 | ``` 422 | 423 | ## Enumerated Types 424 | 425 | When using `enum`s, it is recommended to use the new fixed underlying type specification because it has stronger type checking and code completion. The SDK now includes a macro to facilitate and encourage use of fixed underlying types — `NS_ENUM()` 426 | 427 | **Example:** 428 | 429 | ```objc 430 | typedef NS_ENUM(NSInteger, HYPAdRequestState) { 431 | HYPAdRequestStateInactive, 432 | HYPAdRequestStateLoading 433 | }; 434 | ``` 435 | 436 | ## Private Properties 437 | 438 | Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as `HYPPrivate` or `private`) should never be used unless extending another class. 439 | 440 | **For example:** 441 | 442 | ```objc 443 | @interface HYPAdvertisement () 444 | 445 | @property (nonatomic) GADBannerView *googleAdView; 446 | @property (nonatomic) ADBannerView *iAdView; 447 | @property (nonatomic) UIWebView *adXWebView; 448 | 449 | @end 450 | ``` 451 | 452 | ## Booleans 453 | 454 | Since `nil` resolves to `NO` it is unnecessary to compare it in conditions. Never compare something directly to `YES`, because `YES` is defined to 1 and a `BOOL` can be up to 8 bits. 455 | 456 | This allows for more consistency across files and greater visual clarity. 457 | 458 | **For example:** 459 | 460 | ```objc 461 | if (!someObject) { 462 | } 463 | ``` 464 | 465 | **Not:** 466 | 467 | ```objc 468 | if (someObject == nil) { 469 | } 470 | ``` 471 | 472 | ----- 473 | 474 | **For a `BOOL`, here are two examples:** 475 | 476 | ```objc 477 | if (isAwesome) 478 | if (![someObject boolValue]) 479 | ``` 480 | 481 | **Not:** 482 | 483 | ```objc 484 | if ([someObject boolValue] == NO) 485 | if (isAwesome == YES) // Never do this. 486 | ``` 487 | 488 | ----- 489 | 490 | If the name of a `BOOL` property is expressed as an adjective, the property can omit the “is” prefix but specifies the conventional name for the get accessor, for example: 491 | 492 | ```objc 493 | @property (assign, getter=isEditable) BOOL editable; 494 | ``` 495 | Text and example taken from the [Cocoa Naming Guidelines](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-BAJGIIJE). 496 | 497 | ## Singletons 498 | 499 | Singleton objects should use a thread-safe pattern for creating their shared instance. 500 | ```objc 501 | + (instancetype)sharedInstance { 502 | static id sharedInstance = nil; 503 | 504 | static dispatch_once_t onceToken; 505 | dispatch_once(&onceToken, ^{ 506 | sharedInstance = [[self alloc] init]; 507 | }); 508 | 509 | return sharedInstance; 510 | } 511 | ``` 512 | This will prevent [possible and sometimes prolific crashes](http://cocoasamurai.blogspot.com/2011/04/singletons-your-doing-them-wrong.html). 513 | 514 | ## Attribution 515 | 516 | This document is based on the [NYTimes Objective-C Style Guide](https://github.com/NYTimes/objective-c-style-guide). 517 | -------------------------------------------------------------------------------- /style-guidelines/README.md: -------------------------------------------------------------------------------- 1 | # Hyper's Swift Style Guide 2 | 3 | Our overarching goals are conciseness, readability, and simplicity. 4 | 5 | 1. [Objective-C](ObjC.md) 6 | 2. [Swift](Swift.md) 7 | -------------------------------------------------------------------------------- /style-guidelines/Swift.md: -------------------------------------------------------------------------------- 1 | # Hyper's Swift Style Guide 2 | 3 | Our overarching goals are conciseness, readability, and simplicity. 4 | 5 | When we write Swift code we follow [The Official raywenderlich.com Swift Style Guide](https://github.com/raywenderlich/swift-style-guide) and [The Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/). 6 | --------------------------------------------------------------------------------