[TOC]
1.5 确保不在任何地方出现尾随的空格Xcode->Preferences->Text Editing->Automatically trim trailing whitespace + Including whitespace-only lines
// specifying type
let pirateViewController: PirateViewController
// dictionary syntax (note that we left-align as opposed to aligning colons)
let ninjaDictionary: [String: AnyObject] = [
"fightLikeDairyFarmer": false,
"disgusting": true
]
// declaring a function
func myFunction<T, U: SomeProtocol>(firstArgument: U, secondArgument: T) where T.RelatedType == U {
/* ... */
}
// calling a function
someFunction(someArgument: "Kitten")
// superclasses
class PirateViewController: UIViewController {
/* ... */
}
// protocols
extension PirateViewController: UITableViewDataSource {
/* ... */
}
someFunctionWithManyArguments(
firstArgument: "Hello, I am a string",
secondArgument: resultFromSomeFunction(),
thirdArgument: someOtherLocalProperty)
someFunctionWithABunchOfArguments(
someStringArgument: "hello I am a string",
someArrayArgument: [
"dadada daaaa daaaa dadada daaaa daaaa dadada daaaa daaaa",
"string one is crazy - what is it thinking?"
],
someDictionaryArgument: [
"dictionary key 1": "some value 1, but also some more text here",
"dictionary key 2": "some value 2"
],
someClosure: { parameter1 in
print(parameter1)
})
// PREFERRED
let firstCondition = x == firstReallyReallyLongPredicateFunction()
let secondCondition = y == secondReallyReallyLongPredicateFunction()
let thirdCondition = z == thirdReallyReallyLongPredicateFunction()
if firstCondition && secondCondition && thirdCondition {
// do something
}
// NOT PREFERRED
if x == firstReallyReallyLongPredicateFunction()
&& y == secondReallyReallyLongPredicateFunction()
&& z == thirdReallyReallyLongPredicateFunction() {
// do something
}
// "HTML" is at the start of a constant name, so we use lowercase "html"
let htmlBodyContent: String = "<p>Hello, World!</p>"
// Prefer using ID to Id
let profileID: Int = 1
// Prefer URLFinder to UrlFinder
class URLFinder {
/* ... */
}
// PREFERRED
class MyClassName {
// MARK: - Constants
static let buttonPadding: CGFloat = 20.0
static let indianaPi = 3
static let shared = MyClassName()
}
// NOT PREFERRED
class MyClassName {
// Don't use `k`-prefix
static let kButtonPadding: CGFloat = 20.0
// Don't namespace constants
enum Constant {
static let indianaPi = 3
}
}
// PREFERRED
class RoundAnimatingButton: UIButton {
let animationDuration: NSTimeInterval
func startAnimating() {
let firstSubview = subviews.first
}
}
// NOT PREFERRED
class RoundAnimating: UIButton {
let aniDur: NSTimeInterval
func srtAnmating() {
let v = subviews.first
}
}
// PREFERRED
class ConnectionTableViewCell: UITableViewCell {
let personImageView: UIImageView
let animationDuration: TimeInterval
// it is ok not to include string in the ivar name here because it's obvious
// that it's a string from the property name
let firstName: String
// though not preferred, it is OK to use `Controller` instead of `ViewController`
let popupController: UIViewController
let popupViewController: UIViewController
// when working with a subclass of `UIViewController` such as a table view
// controller, collection view controller, split view controller, etc.,
// fully indicate the type in the name.
let popupTableViewController: UITableViewController
// when working with outlets, make sure to specify the outlet type in the
// property name.
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var nameLabel: UILabel!
}
// NOT PREFERRED
class ConnectionTableViewCell: UITableViewCell {
// this isn't a `UIImage`, so shouldn't be called image
// use personImageView instead
let personImage: UIImageView
// this isn't a `String`, so it should be `textLabel`
let text: UILabel
// `animation` is not clearly a time interval
// use `animationDuration` or `animationTimeInterval` instead
let animation: TimeInterval
// this is not obviously a `String`
// use `transitionText` or `transitionString` instead
let transition: String
// this is a view controller - not a view
let popupView: UIViewController
// as mentioned previously, we don't want to use abbreviations, so don't use
// `VC` instead of `ViewController`
let popupVC: UIViewController
// even though this is still technically a `UIViewController`, this property
// should indicate that we are working with a *Table* View Controller
let popupViewController: UITableViewController
// for the sake of consistency, we should put the type name at the end of the
// property name and not at the start
@IBOutlet weak var btnSubmit: UIButton!
@IBOutlet weak var buttonSubmit: UIButton!
// we should always have a type in the property name when dealing with outlets
// for example, here, we should have `firstNameLabel` instead
@IBOutlet weak var firstName: UILabel!
}
// here, the name is a noun that describes what the protocol does
protocol TableViewSectionProvider {
func rowHeight(at row: Int) -> CGFloat
var numberOfRows: Int { get }
/* ... */
}
// here, the protocol is a capability, and we name it appropriately
protocol Loggable {
func logCurrentState()
/* ... */
}
// suppose we have an `InputTextView` class, but we also want a protocol
// to generalize some of the functionality - it might be appropriate to
// use the `Protocol` suffix here
protocol InputTextViewProtocol {
func sendTrackingEvent()
func inputText() -> String
/* ... */
}
// PREFERRED
let stringOfInts = [1, 2, 3].flatMap { String($0) }
// ["1", "2", "3"]
// NOT PREFERRED
var stringOfInts: [String] = []
for integer in [1, 2, 3] {
stringOfInts.append(String(integer))
}
// PREFERRED
let evenNumbers = [4, 8, 15, 16, 23, 42].filter { $0 % 2 == 0 }
// [4, 8, 16, 42]
// NOT PREFERRED
var evenNumbers: [Int] = []
for integer in [4, 8, 15, 16, 23, 42] {
if integer % 2 == 0 {
evenNumbers.append(integer)
}
}
func pirateName() -> (firstName: String, lastName: String) {
return ("Guybrush", "Threepwood")
}
let name = pirateName()
let firstName = name.firstName
let lastName = name.lastName
myFunctionWithEscapingClosure() { [weak self] (error) -> Void in
// you can do this
self?.doSomething()
// or you can do this
guard let strongSelf = self else {
return
}
strongSelf.doSomething()
}
// PREFERRED
if x == y {
/* ... */
}
// NOT PREFERRED
if (x == y) {
/* ... */
}
// PREFERRED
imageView.setImageWithURL(url, type: .person)
// NOT PREFERRED
imageView.setImageWithURL(url, type: AsyncImageView.Type.person)
// PREFERRED
imageView.backgroundColor = UIColor.white
// NOT PREFERRED
imageView.backgroundColor = .white
if someBoolean {
// do something
} else {
// do something else
}
do {
let fileContents = try readFile("filename.txt")
} catch {
print(error)
}
// PREFERRED
private static let myPrivateNumber: Int
// NOT PREFERRED
static private let myPrivateNumber: Int
// PREFERRED
open class Pirate {
/* ... */
}
// NOT PREFERRED
open
class Pirate {
/* ... */
}
/**
This property defines the pirate's name.
- warning: Not `private` for `@testable`.
*/
let pirateName = "LeChuck"
enum Problem {
case attitude
case hair
case hunger(hungerLevel: Int)
}
func handleProblem(problem: Problem) {
switch problem {
case .attitude:
print("At least I don't have a hair problem.")
case .hair:
print("Your barber didn't know when to stop.")
case .hunger(let hungerLevel):
print("The hunger level is \(hungerLevel).")
}
}
func handleDigit(_ digit: Int) throws {
switch digit {
case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:
print("Yes, \(digit) is a digit!")
default:
throw Error(message: "The given number was not a digit.")
}
}
// PREFERERED
if someOptional != nil {
// do something
}
// NOT PREFERRED
if let _ = someOptional {
// do something
}
guard let myValue = myValue else {
return
}
1. 用`//MARK:`来分割协议的实现和其他部分
2. 在同一个文件中使用类或者结构体的扩展来实现协议
var computedProperty: String {
if someBool {
return "I'm a mighty pirate!"
}
return "I'm selling these fine leather jackets."
}
var storedProperty: String = "I'm selling these fine leather jackets." {
willSet {
print("will set to \(newValue)")
}
didSet {
print("did set from \(oldValue) to \(storedProperty)")
}
}
var computedProperty: String {
get {
if someBool {
return "I'm a mighty pirate!"
}
return storedProperty
}
set {
storedProperty = newValue
}
}
class PirateManager {
static let shared = PirateManager()
/* ... */
}
3.9.1 尽量避免使用下标访问数组,可以使用.first
或者.last
访存器来避免crash。尽可能使用 for in
而不是for i in 0 ..< items.count
。如果确实要使用下标访问要对数组边界情况有判定。推荐使用for (index, value) in items.enumerated()
来遍历数组
// PREFERRED
func eatDoughnut(at index: Int) {
guard index >= 0 && index < doughnuts.count else {
// return early because the index is out of bounds
return
}
let doughnut = doughnuts[index]
eat(doughnut)
}
// NOT PREFERRED
func eatDoughnut(at index: Int) {
if index >= 0 && index < doughnuts.count {
let doughnut = doughnuts[index]
eat(doughnut)
}
}
// PREFERRED
guard let monkeyIsland = monkeyIsland else {
return
}
bookVacation(on: monkeyIsland)
bragAboutVacation(at: monkeyIsland)
// NOT PREFERRED
if let monkeyIsland = monkeyIsland {
bookVacation(on: monkeyIsland)
bragAboutVacation(at: monkeyIsland)
}
// EVEN LESS PREFERRED
if monkeyIsland == nil {
return
}
bookVacation(on: monkeyIsland!)
bragAboutVacation(at: monkeyIsland!)
// combined because we just return
guard let thingOne = thingOne,
let thingTwo = thingTwo,
let thingThree = thingThree else {
return
}
// separate statements because we handle a specific error in each case
guard let thingOne = thingOne else {
throw Error(message: "Unwrapping thingOne failed.")
}
guard let thingTwo = thingTwo else {
throw Error(message: "Unwrapping thingTwo failed.")
}
guard let thingThree = thingThree else {
throw Error(message: "Unwrapping thingThree failed.")
}
// PREFERRED
guard let thingOne = thingOne else {
return
}
// NOT PREFERRED
guard let thingOne = thingOne else { return }