Check If Variable Is an Optional, and What Type It Wraps

Determine if Any.Type is Optional

Assuming that what you are trying to do is something like this:

let anyType: Any.Type = Optional<String>.self
anyType is Optional<Any>.Type // false

Sadly swift currently (as of Swift 2) does not support covariance nor contravariance and type checks directly against Optional.Type cannot be done:

// Argument for generic parameter 'Wrapped' could not be inferred
anyType is Optional.Type // Causes error

An alternative is to make Optional extend an specific protocol, and check for that type:

protocol OptionalProtocol {}

extension Optional : OptionalProtocol {}

let anyType: Any.Type = Optional<String>.self
anyType is OptionalProtocol.Type // true

What is an optional value in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String? = "Bertie"

Optionals (along with Generics) are one of the most difficult Swift concepts to understand. Because of how they are written and used, it's easy to get a wrong idea of what they are. Compare the optional above to creating a normal String:

var name: String = "Bertie" // No "?" after String

From the syntax it looks like an optional String is very similar to an ordinary String. It's not. An optional String is not a String with some "optional" setting turned on. It's not a special variety of String. A String and an optional String are completely different types.

Here's the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int. Think of an optional as a kind of parcel. Before you open it (or "unwrap" in the language of optionals) you won't know if it contains something or nothing.

You can see how optionals are implemented in the Swift Standard Library by typing "Optional" into any Swift file and ⌘-clicking on it. Here's the important part of the definition:

enum Optional<Wrapped> {
case none
case some(Wrapped)
}

Optional is just an enum which can be one of two cases: .none or .some. If it's .some, there's an associated value which, in the example above, would be the String "Hello". An optional uses Generics to give a type to the associated value. The type of an optional String isn't String, it's Optional, or more precisely Optional<String>.

Everything Swift does with optionals is magic to make reading and writing code more fluent. Unfortunately this obscures the way it actually works. I'll go through some of the tricks later.

Note: I'll be talking about optional variables a lot, but it's fine to create optional constants too. I mark all variables with their type to make it easier to understand type types being created, but you don't have to in your own code.



How to create optionals

To create an optional, append a ? after the type you wish to wrap. Any type can be optional, even your own custom types. You can't have a space between the type and the ?.

var name: String? = "Bob" // Create an optional String that contains "Bob"
var peter: Person? = Person() // An optional "Person" (custom type)

// A class with a String and an optional String property
class Car {
var modelName: String // must exist
var internalName: String? // may or may not exist
}


Using optionals

You can compare an optional to nil to see if it has a value:

var name: String? = "Bob"
name = nil // Set name to nil, the absence of a value
if name != nil {
print("There is a name")
}
if name == nil { // Could also use an "else"
print("Name has no value")
}

This is a little confusing. It implies that an optional is either one thing or another. It's either nil or it's "Bob". This is not true, the optional doesn't transform into something else. Comparing it to nil is a trick to make easier-to-read code. If an optional equals nil, this just means that the enum is currently set to .none.



Only optionals can be nil

If you try to set a non-optional variable to nil, you'll get an error.

var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'

Another way of looking at optionals is as a complement to normal Swift variables. They are a counterpart to a variable which is guaranteed to have a value. Swift is a careful language that hates ambiguity. Most variables are define as non-optionals, but sometimes this isn't possible. For example, imagine a view controller which loads an image either from a cache or from the network. It may or may not have that image at the time the view controller is created. There's no way to guarantee the value for the image variable. In this case you would have to make it optional. It starts as nil and when the image is retrieved, the optional gets a value.

Using an optional reveals the programmers intent. Compared to Objective-C, where any object could be nil, Swift needs you to be clear about when a value can be missing and when it's guaranteed to exist.



To use an optional, you "unwrap" it

An optional String cannot be used in place of an actual String. To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a ! after the optional name. This is called "force unwrapping". It returns the value inside the optional (as the original type) but if the optional is nil, it causes a runtime crash. Before unwrapping you should be sure there's a value.

var name: String? = "Bob"
let unwrappedName: String = name!
print("Unwrapped name: \(unwrappedName)")

name = nil
let nilName: String = name! // Runtime crash. Unexpected nil.


Checking and using an optional

Because you should always check for nil before unwrapping and using an optional, this is a common pattern:

var mealPreference: String? = "Vegetarian"
if mealPreference != nil {
let unwrappedMealPreference: String = mealPreference!
print("Meal: \(unwrappedMealPreference)") // or do something useful
}

In this pattern you check that a value is present, then when you are sure it is, you force unwrap it into a temporary constant to use. Because this is such a common thing to do, Swift offers a shortcut using "if let". This is called "optional binding".

var mealPreference: String? = "Vegetarian"
if let unwrappedMealPreference: String = mealPreference {
print("Meal: \(unwrappedMealPreference)")
}

This creates a temporary constant (or variable if you replace let with var) whose scope is only within the if's braces. Because having to use a name like "unwrappedMealPreference" or "realMealPreference" is a burden, Swift allows you to reuse the original variable name, creating a temporary one within the bracket scope

var mealPreference: String? = "Vegetarian"
if let mealPreference: String = mealPreference {
print("Meal: \(mealPreference)") // separate from the other mealPreference
}

Here's some code to demonstrate that a different variable is used:

var mealPreference: String? = "Vegetarian"
if var mealPreference: String = mealPreference {
print("Meal: \(mealPreference)") // mealPreference is a String, not a String?
mealPreference = "Beef" // No effect on original
}
// This is the original mealPreference
print("Meal: \(mealPreference)") // Prints "Meal: Optional("Vegetarian")"

Optional binding works by checking to see if the optional equals nil. If it doesn't, it unwraps the optional into the provided constant and executes the block. In Xcode 8.3 and later (Swift 3.1), trying to print an optional like this will cause a useless warning. Use the optional's debugDescription to silence it:

print("\(mealPreference.debugDescription)")


What are optionals for?

Optionals have two use cases:

  1. Things that can fail (I was expecting something but I got nothing)
  2. Things that are nothing now but might be something later (and vice-versa)

Some concrete examples:

  • A property which can be there or not there, like middleName or spouse in a Person class
  • A method which can return a value or nothing, like searching for a match in an array
  • A method which can return either a result or get an error and return nothing, like trying to read a file's contents (which normally returns the file's data) but the file doesn't exist
  • Delegate properties, which don't always have to be set and are generally set after initialization
  • For weak properties in classes. The thing they point to can be set to nil at any time
  • A large resource that might have to be released to reclaim memory
  • When you need a way to know when a value has been set (data not yet loaded > the data) instead of using a separate dataLoaded Boolean

Optionals don't exist in Objective-C but there is an equivalent concept, returning nil. Methods that can return an object can return nil instead. This is taken to mean "the absence of a valid object" and is often used to say that something went wrong. It only works with Objective-C objects, not with primitives or basic C-types (enums, structs). Objective-C often had specialized types to represent the absence of these values (NSNotFound which is really NSIntegerMax, kCLLocationCoordinate2DInvalid to represent an invalid coordinate, -1 or some negative value are also used). The coder has to know about these special values so they must be documented and learned for each case. If a method can't take nil as a parameter, this has to be documented. In Objective-C, nil was a pointer just as all objects were defined as pointers, but nil pointed to a specific (zero) address. In Swift, nil is a literal which means the absence of a certain type.



Comparing to nil

You used to be able to use any optional as a Boolean:

let leatherTrim: CarExtras? = nil
if leatherTrim {
price = price + 1000
}

In more recent versions of Swift you have to use leatherTrim != nil. Why is this? The problem is that a Boolean can be wrapped in an optional. If you have Boolean like this:

var ambiguous: Boolean? = false

it has two kinds of "false", one where there is no value and one where it has a value but the value is false. Swift hates ambiguity so now you must always check an optional against nil.

You might wonder what the point of an optional Boolean is? As with other optionals the .none state could indicate that the value is as-yet unknown. There might be something on the other end of a network call which takes some time to poll. Optional Booleans are also called "Three-Value Booleans"



Swift tricks

Swift uses some tricks to allow optionals to work. Consider these three lines of ordinary looking optional code;

var religiousAffiliation: String? = "Rastafarian"
religiousAffiliation = nil
if religiousAffiliation != nil { ... }

None of these lines should compile.

  • The first line sets an optional String using a String literal, two different types. Even if this was a String the types are different
  • The second line sets an optional String to nil, two different types
  • The third line compares an optional string to nil, two different types

I'll go through some of the implementation details of optionals that allow these lines to work.



Creating an optional

Using ? to create an optional is syntactic sugar, enabled by the Swift compiler. If you want to do it the long way, you can create an optional like this:

var name: Optional<String> = Optional("Bob")

This calls Optional's first initializer, public init(_ some: Wrapped), which infers the optional's associated type from the type used within the parentheses.

The even longer way of creating and setting an optional:

var serialNumber:String? = Optional.none
serialNumber = Optional.some("1234")
print("\(serialNumber.debugDescription)")


Setting an optional to nil

You can create an optional with no initial value, or create one with the initial value of nil (both have the same outcome).

var name: String?
var name: String? = nil

Allowing optionals to equal nil is enabled by the protocol ExpressibleByNilLiteral (previously named NilLiteralConvertible). The optional is created with Optional's second initializer, public init(nilLiteral: ()). The docs say that you shouldn't use ExpressibleByNilLiteral for anything except optionals, since that would change the meaning of nil in your code, but it's possible to do it:

class Clint: ExpressibleByNilLiteral {
var name: String?
required init(nilLiteral: ()) {
name = "The Man with No Name"
}
}

let clint: Clint = nil // Would normally give an error
print("\(clint.name)")

The same protocol allows you to set an already-created optional to nil. Although it's not recommended, you can use the nil literal initializer directly:

var name: Optional<String> = Optional(nilLiteral: ())


Comparing an optional to nil

Optionals define two special "==" and "!=" operators, which you can see in the Optional definition. The first == allows you to check if any optional is equal to nil. Two different optionals which are set to .none will always be equal if the associated types are the same. When you compare to nil, behind the scenes Swift creates an optional of the same associated type, set to .none then uses that for the comparison.

// How Swift actually compares to nil
var tuxedoRequired: String? = nil
let temp: Optional<String> = Optional.none
if tuxedoRequired == temp { // equivalent to if tuxedoRequired == nil
print("tuxedoRequired is nil")
}

The second == operator allows you to compare two optionals. Both have to be the same type and that type needs to conform to Equatable (the protocol which allows comparing things with the regular "==" operator). Swift (presumably) unwraps the two values and compares them directly. It also handles the case where one or both of the optionals are .none. Note the distinction between comparing to the nil literal.

Furthermore, it allows you to compare any Equatable type to an optional wrapping that type:

let numberToFind: Int = 23
let numberFromString: Int? = Int("23") // Optional(23)
if numberToFind == numberFromString {
print("It's a match!") // Prints "It's a match!"
}

Behind the scenes, Swift wraps the non-optional as an optional before the comparison. It works with literals too (if 23 == numberFromString {)

I said there are two == operators, but there's actually a third which allow you to put nil on the left-hand side of the comparison

if nil == name { ... }


Naming Optionals

There is no Swift convention for naming optional types differently from non-optional types. People avoid adding something to the name to show that it's an optional (like "optionalMiddleName", or "possibleNumberAsString") and let the declaration show that it's an optional type. This gets difficult when you want to name something to hold the value from an optional. The name "middleName" implies that it's a String type, so when you extract the String value from it, you can often end up with names like "actualMiddleName" or "unwrappedMiddleName" or "realMiddleName". Use optional binding and reuse the variable name to get around this.



The official definition

From "The Basics" in the Swift Programming Language:

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.


To finish, here's a poem from 1899 about optionals:

Yesterday upon the stair

I met a man who wasn’t there

He wasn’t there again today

I wish, I wish he’d go away


Antigonish



More resources:

  • The Swift Programming Guide
  • Optionals in Swift (Medium)
  • WWDC Session 402 "Introduction to Swift" (starts around 14:15)
  • More optional tips and tricks

Checking optional isEqualToString

Optional has an == operator defined for it in the Swift standard library:

func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool

That means if the optional contains a value that’s equatable, you can compare two optionals. If the two optionals are both nil they’re equal, and if the two optionals wrap values that are equal, then they’re equal.

So if you don’t care about whether person.name is nil or not, just whether it contains a value of "John", you can just write if person.name == "John".

How does that work, when "John" is a String not a String??* Because Swift will implicitly convert any type to an optional wrapping that type if that’s what an argument requires. So because the == function for comparing optionals requires a String? argument, “John” will be implicitly converted to {Some "John"}, allowing the == operator between two optionals to be used.

* well actually "John” isn't a String either, it’s a string literal that is getting converted into a String

How to unwrap an optional value from Any type?

For Xcode 7 and Swift 2:

func unwrap(any:Any) -> Any {

let mi = Mirror(reflecting: any)
if mi.displayStyle != .Optional {
return any
}

if mi.children.count == 0 { return NSNull() }
let (_, some) = mi.children.first!
return some

}


let int:Int? = 1
let str:String? = "foo"
let null:Any? = nil
let values:[Any] = [unwrap(int),2,unwrap(str),"bar", unwrap(null)]

This will give you [1, 2, "foo", "bar", {NSObject}]

Change NSNull() to nil and the return value of unwrap func to Any? will always unwrap any type.

How to get the unwrapped type from an optional type in Swift?

I played with your idea a little bit, but I think there isn't a real way to do that, since you can't get the type of the associated value of an enumeration, yet. Hence Optionals are basically Enumerations, we have a problem here.

My idea would be to test for all possible value types in your model objects could be or hold. Like:

let myModelObject:Any? = someWayToGetTheData()
if let aString = myModelObject as? String {
// do everything you need to store a string
}
else if let anInteger = myModelObject as? Int {
// do everything you need to store an integer
}

// and so on ...

Since your json and your model must have a predefined number of supported conversions that is a possible way, and as far as I understand your original problem, it's basically as useful as testing for the dynamic associated value type of an Optional Enumeration, which will lead into a chain of if-else statements as well.

How to check if is null and if has a specific value using Optional in java?

Use Optional<Integer>

public List<T> getAll(Integer paramter) {
return Optional.ofNullable(parameter)
.filter(p -> p > -1);
}

The Optional<> is just an implementation of Optional pattern. The useful methods is also Optional<T>#orElse(T default) which sets the value to default in case there was a null,

If you already got interested but still can't answer your doubts, please ask for clarification in comments. I'll respond asap.

Optional variable take action based on its value

Personally, I would not pass an Optional as parameter in this case.

In this case, I would code it like

var projects = Optional.of("the-analyst-id")
.map(id -> getProjectsByAnalist(id))
.orElseGet(()-> getAllProjects());

You can optionally wrap that in a function (like you did before).

Method ifPresentOrElse() does not return a value and is mainly an operator meant for running side effects.

The .map().orElseGet() idiom is the similar, but returns the value.

Checking the value of an Optional Bool

With optional booleans it's needed to make the check explicit:

if boolean == true {
...
}

Otherwise you can unwrap the optional:

if boolean! {
...
}

But that generates a runtime exception if boolean is nil - to prevent that:

if boolean != nil && boolean! {
...
}

Before beta 5 it was possible, but it has been changed as reported in the release notes:

Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.

Addendum: as suggested by @MartinR, a more compact variation to the 3rd option is using the coalescing operator:

if boolean ?? false {
// this code runs only if boolean == true
}

which means: if boolean is not nil, the expression evaluates to the boolean value (i.e. using the unwrapped boolean value), otherwise the expression evaluates to false



Related Topics



Leave a reply



Submit