Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift comparing Strings optionals vs non-optional

Tags:

ios

swift

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?

like image 279
WYS Avatar asked Jul 26 '16 10:07

WYS


People also ask

When should you use optionals Swift?

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.

Why do we use optionals?

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.

What is unconditional unwrapping in Swift?

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.

What is optional variable in Swift?

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.


2 Answers

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.

like image 74
Sulthan Avatar answered Sep 30 '22 20:09

Sulthan


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.

like image 30
Jack Greenhill Avatar answered Sep 30 '22 18:09

Jack Greenhill