Balancing Literals and Types

Although the Swift compiler infers typing for literals like 2 and “Hello,” you will never cause an error or reduce safety by explicitly typing declarations. Consider the following examples:

 var​ aDouble = 23 ​// no, terrible variable name
 let​ aFloat = 23 ​as​ ​Float​ ​// not preferred
 let​ anotherDouble: ​Double​ = 23 ​// yes
 var​ anotherFloat: ​Float​ = 23 ​// yes

Casting needlessly distances types from variable and constant names. A type should describe a symbol, not the value that’s being stored in it, so keep the type name close to its symbol:

 let​ freezingPoint: ​CGFloat​ = 32.0 ​// yes
 let​ freezingPoint = 32.0 ​as​ ​CGFloat​ ​// no

Mix-and-match inferencing creates inconsistent code. ...

Get Swift Style, 1st Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.