rspec/rules/S2967/swift/rule.adoc

38 lines
1.0 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
The point of using an optional is to signal that the value may be ``++nil++`` and to provide graceful ways of dealing with it if it is ``++nil++``. While implicitly unwrapped optionals still provide means of dealing with ``++nil++`` values, they also signal that the value won't be ``++nil++``, and unwrap it automatically. In addition to sending a decidedly mixed signal, this could lead to runtime errors if the value ever is ``++nil++``.
It is safest, and clearest to use either an optional or a plain type and avoid the boggy middle ground of implicitly unwrapped optionals.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,swift]
2021-04-28 16:49:39 +02:00
----
var greeting : String! // Noncompliant
println(greeting) // At this point the value is nil. Runtime error results
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,swift]
2021-04-28 16:49:39 +02:00
----
var greeting : String?
if let howdy = greeting {
println(howdy)
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]