rspec/rules/S2966/swift/rule.adoc

49 lines
1.0 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
The point of declaring an optional variable is to make explicit the fact that it might contain no valid value, i.e. ``++nil++``. Force-unwrapping an optional will lead to a runtime error if the optional does contain ``++nil++``. Even if the value is tested first, it's still considered a bad practice to use force-unwrapping. Instead, optional binding or optional chaining should be used.
=== Noncompliant code example
[source,swift]
----
var greeting: String?
// ...
println( \(greeting!)) // Noncompliant; could cause a runtime error
if greeting != nil {
println( \(greeting!)) // Noncompliant; better but still not great
}
----
=== Compliant solution
[source,swift]
----
var greeting: String?
// ...
if let howdy = greeting {
println(howdy)
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]