Passing `NSNumber.init` or `NSDecimalNumber.init` as a function reference is dangerous as it can cause the wrong initializer to be used, causing crashes; use `.init(value:)` insteadSW-W1030
Passing NSNumber.init
or NSDecimalNumber.init
as a function reference in Swift can lead to unexpected behavior and potential crashes. This issue arises because using init as a function reference can result in the wrong initializer being used, leading to incorrect initialization and runtime errors.
When using NSNumber.init
or NSDecimalNumber.init
as a function reference, the compiler infers the type of the initializer based on the context. This can be problematic because these classes have multiple initializers with different parameter types. If the inferred initializer does not match the intended one, it can cause crashes or incorrect behavior at runtime.
To fix this issue, it is recommended to use the designated initializer explicitly by using .init(value:)
instead of relying on the default initializer (init). This ensures that the correct initializer is used and reduces the risk of runtime errors.
Bad Practice
[0, 0.2].map(NSNumber.init)
Recommended
[0, 0.2].map(NSNumber.init(value:))