Prefer `.zero` over explicit init with zero parametersSW-R1009
Using the .zero
initializer in Swift is generally more readable and concise
than using a custom initializer with zero arguments when initializing an object
with default values. Here are a few reasons why:
Readability: The .zero
initializer is a property that expresses a clear
intention of initializing the object with default values. It is more readable
and less verbose than using a custom initializer with zero arguments, which can
be confusing to read, especially in cases where there are multiple
initializers.
Reduced Boilerplate: Using the .zero
initializer reduces boilerplate code and
makes it easier to maintain the codebase. It also eliminates the need for a
custom initializer with zero arguments, which can be error-prone and lead to
inconsistencies in the codebase.
Consistency: The .zero
initializer is consistent across different types and
structures in Swift, making it easier to learn and use. It also provides a
standardized way of initializing objects with default values, improving the
consistency of the codebase.
In summary, using the .zero
initializer is a best practice in Swift. It
improves readability, reduces boilerplate, and promotes consistency. It is
recommended to use .zero
instead of a custom initializer with zero arguments
whenever possible.
Bad Practice
let point = CGPoint.init()
let size = CGSize.init(width: 0, height: 0)
Recommended
let point = CGPoint.zero
let size = CGSize.zero