wnagrodzki / iOSProgrammingGuidelines

2 stars 0 forks source link

Declarations #6

Closed wnagrodzki closed 6 years ago

wnagrodzki commented 6 years ago

Do not declare type if compiler is able to infer it.

let string = "a string"
let double = 1.0
let int = 1
let array = [1, 2, 3]
let dictionary = [1: "one", 2: "two"]

This is to minimize clutter.

Keep type on the right hand side of assignment operator (this rule does not apply for closures, declare the type wherever it helps readability).

let height = CGFloat(44)
let duration = NSTimeInterval(0.25)
let view = UIView()
var array = [Int]()
var dictionary = [Int: String]()

let accumulator: (Int, Int) -> Int = { $0 + $1 }

Since not all the types can be declared by a literal and type on the left hand side of assignment operator (e.g. let height: CGFloat = 20), let's keep all the types on the right side.

Declare constants within appropriate type.

class PhysicalObject {
    /// N * m^2 * kg^-2
    static let gravitationalConstant = 6.667e-11
}

This is to increase discoverability and avoid global namespace pollution.

Gather IBOutlets in one group above all the other properties and keep them private.

@IBOutlet private weak var view: UIView!

Outlets are implementation detail and should be kept private. Gathering them in one grup above all the other properties is old convention.

pwetrifork commented 6 years ago

I am wondering about some examples when declaring closure variables, the "type is kept on the right side of the assignment operator" rule sometimes results in quite verbose closure headers.

wnagrodzki commented 6 years ago

@pwetrifork Which definition do you prefer the most, or maybe you want to provide an example?

let closure1: (Int, Int) -> Int = { $0 + $1 }

let closure2: (Int, Int) -> Int = { (a, b) in
    a + b
}

let closure3 = { (a: Int, b: Int) -> Int in
    return a + b
}
pwetrifork commented 6 years ago

I like 2 more than 3 and for simple closures, I would never pick 3 over 1. That's why I had reservations about the general "type to the right of assignment" rule.

wnagrodzki commented 6 years ago

@pwetrifork Point taken, I added exception from this rule for closures

pwetrifork commented 6 years ago

Looking fine