Use type annotation as little as possible when declaring a constant or a variable; instead let the compiler infer the variable type. This convention does not apply to properties.
Type inference helps reduces line noise and maintain clearer code.
When assigning an enum or a static property to a variable or a constant, if the type of the variable or the constant is known, use the shorthand dot syntax to access the enum or static property.
func layout(with direction: NSUserInterfaceLayoutOrientation) {
switch direction {
case .horizontal:
layoutHorizontally()
case .vertical:
layoutVertically()
}
}
func layout(with direction: NSUserInterfaceLayoutOrientation) {
switch direction {
case NSUserInterfaceLayoutOrientation.horizontal:
layoutHorizontally()
case NSUserInterfaceLayoutOrientation.vertical:
layoutVertically()
}
}
Let the compiler infer the type of a constant or variable whenever possible.
let horizontalMargin = 10
let font = NSFont.systemFont(ofSize: 15.0)
let horizontalMargin: Int = 10
let font: NSFont = NSFont.systemFont(ofSize: 15.0)
Use type annotations instead of type inference for properties for API clarity.
class CustomLabel {
let textColor: UIColor = .white
}
class CustomLabel {
let textColor = UIColor.white
}