Last active
March 8, 2019 00:53
-
-
Save davidolesch/2be7dcfcce8cf4185f09fac92af2759c to your computer and use it in GitHub Desktop.
Good Swift Style and Conventions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
____ _ __ _ | |
/ ___|_ _(_)/ _| |_ | |
\___ \ \ /\ / / | |_| __| | |
___) \ V V /| | _| |_ | |
|____/ \_/\_/ |_|_| \__| | |
Good Swift Style and Conventions | |
March 2019 Austin iPhone Developer Meetup | |
*/ | |
// 1. Delegate Protocol should be constrained to type of class | |
protocol SomeDelegate: class { | |
func didTapCell() | |
} | |
weak var delegate: SomeDelegate? | |
// 2. Colon Spacing | |
var cost:Double = 2.00 // Bad. | |
var price : Double = 3.00 // Bad. | |
var profit: Double = 1.00 // Good! | |
// 3. Comma Spacing in functions | |
func sum(a:Int,b:Int) -> Int { // Bad. | |
return a + b | |
} | |
func product(a: Int, b: Int) -> Int { // Good! | |
return a * b | |
} | |
// 4. Control Statement Parentheses are Unnecessary | |
if (cost != 0) { // Bad. | |
print("It's not free.") | |
} | |
if cost == 0 { // Good! | |
print("It's free!") | |
} | |
// 5. Identifier Name | |
var num = 0 // Bad. | |
var theNumberOfTimesThatTheUserHasTappedOnTheLogInButton = 0 // Bad | |
var LoginTapCount = 0 // Bad. | |
var loginTapCount = 0 // Good! | |
// 6. Redundant Set Access Control Rule | |
internal(set) var youCanSetMe: Int // Bad. | |
public var doNotSetMe: Int // Good! | |
// 7. Trailing Comma | |
let oddNumbers = [1, 3, 5, 7, 9,] // Bad. | |
let evenNumbers = [0, 2, 4, 6, 8] // Good! | |
// 8. Duplicate Imports | |
import Foundation | |
import UIKit | |
import MapKit | |
import Foundation // Bad. | |
import HealthKit | |
// 9. For Where | |
for number in evenNumbers { | |
if number > 0 { | |
print(number) // Positive even number. | |
} | |
} | |
for number in evenNumbers where number > 0 { | |
print(number) | |
} | |
// 10. Don't Force Cast | |
class General { | |
} | |
class Specific: General { | |
func run() { } | |
} | |
let object = Specific() | |
let specific = object as! Specific | |
specific.run() | |
print(String(describing: specific.self)) | |
//let numberSquared = product(a: number, b: number) // Bad. | |
if let number = Int(exactly: 3.00) { | |
let numberSquared = product(a: number, b: number) // Good! | |
print(numberSquared) | |
} | |
func squareIfYouCan() { | |
guard let number = Int(exactly: 3.14) else { return } | |
let numberSquared = product(a: number, b: number) // Good! | |
print(numberSquared) | |
} | |
// Automate this using SwiftLint https://github.com/realm/SwiftLint |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment