When comparing strings in Swift, you can compare non-optional strings with optional strings.
Like so (text is an optional, and it is empty):
UITextField.text == "" // True
Is it because the equality operator unwraps Strings by itself?
Optional types or Optionals in Swift You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn't a value at all.
Optionals are in the core of Swift and exist since the first version of Swift. An optional value allows us to write clean code with at the same time taking care of possible nil values. If you're new to Swift you might need to get used to the syntax of adding a question mark to properties.
Unconditional UnwrappingWhen you're certain that an instance of Optional contains a value, you can unconditionally unwrap the value by using the forced unwrap operator (postfix ! ). For example, the result of the failable Int initializer is unconditionally unwrapped in the example below.
An optional in Swift is basically a constant or variable that can hold a value OR no value. The value can or cannot be nil. It is denoted by appending a “?” after the type declaration.
For every Equatable
type the ==
operation is also defined for optionals:
public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool
The non-optional on the right side gets automatically promoted to an optional.
The ==
for optionals returns true
when both values are nil
or if they are both non-nil and they are equal.
Your theory doesn’t hold in the following example:
let x: String? = nil
if x == "" {
print("True")
} else {
print("False") //Printed
}
What’s actually happening here is that the text
property is never actually nil
upon initialisation — it is instead an empty string, as given by the documentation:
This string is @"" by default.
The Swift compiler does not implicitly unwrap any optionals, it instead leaves that responsibility to the programmer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With