Why can you assign non-optional values to optional types in Swift? - swift

Why do assignments involving Swift optionals type check?
For example in,
var foo : Int? = 0
foo = foo!
foo and foo! do not have the same type. Shouldn't you need to wrap the unwrapped value to assign it to an optional type?

This is part of the syntactic sugar behind optionals. Assigning a non-optional value is how you wrap it in the optional type.
Since an optional indicates the presence or absence of a value, you shouldn't have to do anything special to indicate the presence of a value other than provide one. For example, in a function:
func gimmeSomethingMaybe() -> String? {
if arc4random_uniform(10) > 7 {
return "something"
} else {
return nil
}
}
Imagine if every time you wanted to return a real value from a function that's capable of returning nil, you had to write return Optional(value). That'd get old pretty fast, right? Optionals are an important feature of the language — even though they're actually implemented by the standard library, the syntactic sugar / automatic wrapping is there to keep it from being tedious to use them.
Edit: just to go a bit further into this... the sugar also helps to enforce the notion that a real value should not be optional. For example:
let one = 1
one? // error (in Swift 1.2, allowed but meaningless in Swift 1.1)
"two"? // error (ditto)
You can create an optional wrapping a real value with the Optional(one) initializer, but that has little semantic meaning on its own, so you almost never need to.
Optionals should come into play when there's "mystery" as to whether a value is present or absent — that is, when whether one part of a program receives a value (or no value) depends on state unknown to that part of the program. If you know you have a real value, there's no mystery... instead, you let the unknown come into play at the boundary between the code that knows the value and the code that doesn't know — that is, the function/method/property definition that hands that value off to somewhere.

After reading rickster's answer, I came up with a simple laymen terms answer. To me the whole whole gist of his answer is
Since an optional indicates the presence or absence of a value, you
shouldn't have to do anything special to indicate the presence of a
value other than provide one
An optional is an enum. Which has 2 cases a or b.
String?
|
An enum with 2 cases
|
a b
| |
Set notSet
| |
any value like "hi" nil
So you could do either of the things when you want to assign to an optional.
Say the value is either:
a: it's set to "hi"
b: it's not set, so it's nil
c: it just equals to another enum ie another optional
code:
var str : String?
var anotherOptional : String?
str = nil // nil <-- this is like case b
str = "hi" // "hi" <-- this is like case a
str = anotherOptional // nil <-- this is like case c
anotherOptional = "hi again"
str = anotherOptional // "hi again" <-- this is like case c

Related

Optional chaining with Swift strings

With optional chaining, if I have a Swift variable
var s: String?
s might contain nil, or a String wrapped in an Optional. So, I tried this to get its length:
let count = s?.characters?.count ?? 0
However, the compiler wants this:
let count = s?.characters.count ?? 0
My understanding of optional chaining is that, once you start using ?. in a dotted expression, the rest of the properties are made optional and are typically accessed by ?., not ..
So, I dug a little further and tried this in the playground:
var s: String? = "Foo"
print(s?.characters)
// Output: Optional(Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x00000001145e893f, _countAndFlags: 3, _owner: nil)))
The result indicates that s?.characters is indeed an Optional instance, indicating that s?.characters.count should be illegal.
Can someone help me understand this state of affairs?
When you say:
My understanding of optional chaining is that, once you start using ?. in a dotted expression, the rest of the properties are made optional and are typically accessed by ?., not ..
I would say that you are almost there.
It’s not that all the properties are made optional, it’s that the original call is optional, so it looks like the other properties are optional.
characters is not an optional property, and neither is count, but the value that you are calling it on is optional. If there is a value, then the characters and count properties will return a value; otherwise, nil is returned. It is because of this that the result of s?.characters.count returns an Int?.
If either of the properties were optional, then you would need to add ? to it, but, in your case, they aren’t. So you don’t.
Edited following comment
From the comment:
I still find it strange that both s?.characters.count and (s?.characters)?.count compile, but (s?.characters).count doesn't. Why is there a difference between the first and the last expression?
I’ll try and answer it here, where there is more room than in the comment field:
s?.characters.count
If s is nil, the whole expression returns nil, otherwise an Int. So the return type is Int?.
(s?.characters).count // Won’t compile
Breaking this down: if s is nil, then (s?.characters) is nil, so we can’t call count on it.
In order to call the count property on (s?.characters), the expression needs to be optionally unwrapped, i.e. written as:
(s?.characters)?.count
Edited to add further
The best I can get to explaining this is with this bit of playground code:
let s: String? = "hello"
s?.characters.count
(s?.characters)?.count
(s)?.characters.count
((s)?.characters)?.count
// s?.characters.count
func method1(s: String?) -> Int? {
guard let s = s else { return nil }
return s.characters.count
}
// (s?.characters).count
func method2(s: String?) -> Int? {
guard let c = s?.characters else { return nil }
return c.count
}
method1(s)
method2(s)
On the Swift-users mailing list, Ingo Maier was kind enough to point me to the section on optional chaining expressions in the Swift language spec, which states:
If a postfix expression that contains an optional-chaining expression is nested inside other postfix expressions, only the outermost expression returns an optional type.
It continues with the example:
var c: SomeClass?
var result: Bool? = c?.property.performAction()
This explains why the compiler wants s?.characters.count in my example above, and I consider that it answers the original question. However, as #Martin R observed in a comment, there is still a mystery as to why these two expressions are treated differently by the compiler:
s?.characters.count
(s?.characters).count
If I am reading the spec properly, the subexpression
(s?.characters)
is "nested inside" the overall postfix expression
(s?.characters).count
and thus should be treated the same as the non-parenthesized version. But that's a separate issue.
Thanks to all for the contributions!

Swift Optionals - Syntax logic

Looking at this example of conditionals I am confused.
Here is the code and my interpretation
var animal = Animal(name: "Lenny", species: "lemur", tailLength: 12)
animal = Animal(name: "Gilbert", species: "Gorilla", tailLength: nil )
if let tailLength = animal.tail?.length {
print("\(animal.name)'s tail is \(tailLength) long")
} else {
print("\(animal.name) doesn't have a tail.")
}
We have a variable "Animal". Not all animals have tails and so some tailLength values will return nil.
To me, an optional is something with options - in this case it can be an Int or nil (In the case of Gilbert above).
Now, when we want to unwrap it, we are using chaining to check if it will return nil. If it returns an Int, we return it. If it returns nil, we move to the else statement.
Why is the syntax -
if let tailLength = animal.tail?.length
rather than
if let tailLength = animal.taillength?
or
if let tailLength = animal.tail.length?
Note: New to programming. I'm aware that perhaps the answer requires some prerequisite knowledge of other languages and common syntax.
Let's clear this up.
First some prerequisites…
Optionals
Optionals do not necessarily imply options. Instead, "optional" simply implies that the value may or may not exist, hence it is "optional". Think of Optionals as containers sized just right so that they may only hold one specific type. For example, an Optional created specifically to hold an Int could never hold a String, and vice versa. By this definition, Optionals sound exactly the same as variables and constants, but the big difference to note is that unlike regular variables and constants, the containers for Optionals may contain "no value at all", AKA nil or they may contain a value of their specified type. There are no other options.
Optionals are used anytime it makes sense for there to be no value at all, since nil is a better representation of "nothing" than say, -1 for an Integer.
For example,
class Contact {
var name: String
var phoneNumber: String?
var emailAddress: String?
init(name: String, number: String?, emailAddress: String?) {
self.name = name
self.phoneNumber = number
self.emailAddress = emailAddress
}
}
This is a vastly simplified version of what you might use to represent an entry in a contacts app. For simplicity, we'll use Strings to represent each of these properties. The question mark after the type name means that we do not want these properties to be of type String, but instead String?, or "Optional String". The app requires the user to enter their name, but the user may or may not choose to provide a phone number or email address, so the corresponding properties are declared as optional Strings. If the user provides an email address, for example, then the emailAddress property will hold a String representing the address. If the user had not provided an address, the emailAddress property would not hold a String but instead nil, or the absence of a value.
Behind the scenes, an Optional is just an enumeration with two cases: None, and Some with a wrapped value of the type the optional was declared. If you're not familiar with Swift enumerations or this is confusing to you, please ignore this paragraph. It is not important in order to understand Optionals.
Optionals always have only two options. Either nil or a value of the type they were declared.
Unwrapping Optionals
Now suppose we want to access an Optional at some point. We can't just reference it because there is a possibility that it could be nil and our calculation wouldn't function properly. For example, if we wanted to access the user's email address, we might try something like
let user = Contact(name: "Matt", number: nil, emailAddress: nil)
sendEmail(user.emailAddress)
Assuming that the sendEmail function requires a String representing the address as an argument, Swift will report an error and not let the code compile as is. The problem is that we cannot guarantee that there will actually be a String to pass sendEmail. sendEmail requires a String but we are trying to pass it a String?. These are not the same type. If we know that the value will indeed exist, we can just append an exclamation mark immediately after the value that is optional. So, continuing with our example,
let user = Contact(name: "Matt", number: nil, emailAddress: nil)
sendEmail(user.emailAddress!)
Here, the exclamation mark tells Swift that we are sure there will be a value in the emailAddress property, so Swift goes ahead and converts the String? to a String with the value. If at runtime it turns out that emailAddress evaluates to nil, we will get a fatal error. Of course, in this case, we will get a fatal error at runtime because emailAddress did indeed contain nil.
Much of the time, however, and especially in our Contact example, we will not be able to guarantee that a emailAddress exists. Now introducing Optional Binding…
Optional Binding
For times when we simply do not know whether a value exists, but would like to use that value for something if it does, we can use Optional Binding.
Suppose we want to send the user an email if they provided their address. Well, we would need to ensure the value is not nil, assign it to a constant if it isn't, and do some workaround if it is. Here's a perfectly valid way of doing so:
if user.emailAddress != nil {
let address = user.emailAddress!
sendEmail(address)
} else {
promptForEmailAddress()
}
Here, we are checking to make sure the address is not nil. If it is, we will ask the user to give it to us. If the address does exist (if it's not nil), we will assign it to a constant by force unwrapping it with an exclamation mark. We can do this because if the if statement resolves to true, we can be absolutely certain that user.emailAddress will not be nil. sendEmail is then satisfied because address is of type String and not String?, since we unwrapped it first.
But because this is such a common pattern in Swift, the language defines a simplified way of doing this (Optional Binding). The following code snippet is exactly equivalent to the snippet above.
if let address = user.emailAddress {
sendEmail(address)
} else {
promptForEmailAddress()
}
With optional binding, you combine the assignment operation with the if statement. If whatever is on the right of the equals operator (assignment operator) evaluates to nil, the else clause is called and the address constant is never created. If, however, the expression on the right of the equals operator does indeed contain a value, in this case a String, then the address constant is created and initialized with whatever String value was stored in emailAddress. The type of address is therefore String and not String? because if the constant is created, we know it is not nil.
Optional Chaining
Now, sometimes you need to access properties that are at the end of a long chain of objects. For example, suppose emailAddress was not a String but instead a special Email object that held several properties of its own, including a domainName declared as a 'String'.
visitWebAddress(user.emailAddress.domainName)
If one of these values (user, emailAddress, or domainName) was declared as an Optional, this would not be a safe call and Swift would yell at us because our imaginary visitWebAddress function expects a String, but got a String?. Actually, this is not even valid code because we should have a ? after emailAddress. What's going on here? Well, remember that emailAddress was declared as a String?, or "optional string". Anytime we want to access a property using dot syntax on an already optional value, we must use either an exclamation mark (which forces the Optional unwrapped and returns the value which must exist) or a question mark. Whether we choose ! or ?, the symbol must immediately follow the property that was declared to be Optional.
visitWebAddress(user.emailAddress?.domainName)
This statement is syntactically correct. The question mark tells Swift that we realize emailAddress could be nil. If it is, the value of the entire statement user.emailAddress?.domainName will be nil. Regardless of whether emailAddress actually is nil or not, the resulting type of user.emailAddress?.domainName will be String?, not String. Therefore, Swift will still yell at us because visitWebAddress expected a String, but got a String?.
Therefore, we could use a combination of Optional Binding and Optional Chaining to create a simple and elegant solution to this problem:
if let domain = user.emailAddress?.domainName {
visitWebAddress(domain)
}
Remember, the expression on the right side of the equal operator is evaluated first. As already discussed, user.emailAddress?.domainName will evaluate to a String? that will be nil if the email address was not specified. If this is the case and the expression evaluates to nil, no constant is ever created and we are done with the if statement. Otherwise, the value is bound (hence "Optional Binding") to a created constant domain (which will have type String) and we can use it inside the if clause.
As a side note, Optional Chaining can sometimes result in no action at all taking place when a value is nil. For example,
textField?.text = "Hello"
Here, if textField evaluates to nil (for example if the UI has not loaded yet), the entire line is skipped and no action is taken.
Now for your exact question,
Code Analysis
Based on your posted code sample, this is what is likely going on. The Animal class probably looks something like this at a minimum:
class Animal {
let name: String
let species: String
let tail: Tail?
init(name: String, species: String, tailLength: Int?) {
self.name = name
self.species = species
if let lengthOfTail = tailLength {
self.tail = Tail(length: lengthOfTail)
}
}
}
Now, you're probably wondering what is up with all this mention of a Tail object, so this is probably also existent somewhere behind the scenes, looking like this at a minimum:
class Tail {
let length: Int
init(length: Int) {
self.length = length
}
}
(Now going back and looking at Animal should make more sense.)
Here, we have a Tail object with one property called length, of type Int (not optional). The Animal class, however, contains a property called 'tail' which is of type Tail?, or "optional Tail". This means that an Animal may or may not have a tail, but if it does it is guaranteed to have a length of type Int.
So here…
if let tailLength = animal.tail?.length {
print("\(animal.name)'s tail is \(tailLength) long")
} else {
print("\(animal.name) doesn't have a tail.")
}
…a ? immediately follows tail because it is the property that is optional. The statement animal.tail?.length has a type of Int? and if it is nil because tail is nil, the else clause is called. Otherwise, a constant tailLength is created and the tail length as an Int is bound to it.
Note that in the Animal initializer, it simply took an Int? for tailLength, but behind the scenes it checked to see if it was nil and only if it wasn't did it create a Tail object with the specified length. Otherwise, the tail property on the Animal was left nil, since nil is the default value of a non-initialized optional variable or constant.
Hope that clears up all of your questions on Optionals in Swift. The Swift Language Guide has some great content on this, so check it out if needed.

little confuse about optionals in swift

Maybe I'm very confused idk yet. I thought i understood the basic concept but when playing around in xcode I'm not getting what I thought I should be
Take the following code
var title: String? = "hello world"
println("\(title)")
I thought that this would give me an error because I thought that title should have to be unwrapped since I;m accessing it, but it seems to compile just fine. Can someone shed some light on this.
Optionals are Printables, meaning you can print them to an output stream (here the console). You should see something like Optional("hello world") in your console and not hello world
All an optional is is that if it is nil, the app won't crash. If you put the elimination mark, and did not assign a value, it would crash.
In an if statement, you can check if the variable is nil:
if (title == nil) {
//this works
}
As per documentation, your statement will be converted to
var title: Optional<String> = Some("hello world").
From Apple documentation, Optional is
enum Optional<A> {
case Nil
case Some(A)
}
So when you are passing a value to an optional, at the time of declaration, compiler understands, it has got a value and that's why it is not showing error.
But if you do the below code you may get different result.
var title: String? = "hello world"
title = nil
println("\(title)")
It will print "nil" in playground.
Based on apple doc
The concept of optionals doesn’t exist in C or Objective-C. The
nearest thing in Objective-C is the ability to return nil from a
method that would otherwise return an object, with nil meaning “the
absence of a valid object.” However, this only works for objects—it
doesn’t work for structures, basic C types, or enumeration values. For
these types, Objective-C methods typically return a special value
(such as NSNotFound) to indicate the absence of a value. This approach
assumes that the method’s caller knows there is a special value to
test against and remembers to check for it. Swift’s optionals let you
indicate the absence of a value for any type at all, without the need
for special constants.
Example
let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation mark
Reference: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
var title: String? = "hello world"
println("\(title)") // This would print out Optional(Title)
var title2: String! = "hello world"
println("\(title2)") // This would print in Title
Optional do not cause your program to crash when they are executed without a value but !(variable) will cause your code to crash if they have no value.
Swift documentation:
As described above, optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with an if statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional’s value if it does exist.

It it okay to access an optional variable with question mark without exclamation mark?

I know that an optional constant or variable with a question mark needs an exclamation mark to access its value. then, I tried to exam it with the following code.
var aaa:String? = "3"
println("aaa = \(aaa!)")
Yes. It was okay. It printed "3" on Console Output. and next exam I tried like that
var aaa:String? = "3"
println("aaa = \(aaa)")
It also printed "3" without any error message. It worked well.
I learned about Forced Unwrapping that en exclamation mark is needed to access to a value of Optional. But, I could access it without the mark. Is it right? I wonder what is wrong. Am I misunderstanding Optional?
You are correctly understanding Optionals and Forced Unwrapping. The reason that you can print the optional variable is that the type Optional can also be printed. If you print an Optional instead of the real value, it will either print the value if it has one, or "nil" if it doesn't.
Also, just in case you don't realize it. Forced Unwrapping will cause the whole program to crash if the optional is nil at the time. To be safer, you should use Optional Binding:
var aaa: String? = "3"
if let actualString = aaa {
// actualString becomes a non-optional version of aaa
// if aaa were nil, this block would not be run at all
println(actualString)
}
Also, some extra information about the printing of instances. Printing uses the protocol Printable which defines a description property. Anything that implements this protocol can customize the way they print out. Optional has its own implementation of this protocol which is how it decides to either print "nil" or the description of the actual value.
Println() will print the value if it has any otherwise it will print nil. Just to understand things better just try to assign value of aaa to another string variable. It will throw error that value of optional type not unwrapped.
var aString:NSString? = "Hello"
var bString = aString // Compiler allows, as you are assigning to optional type again.
var cString:NSString = aString // Compiler throws error. You cannot assign optional type without unwrapping.
So to answer your question you need to use ! to get the value.
Edit:
var foo:Bool?
foo = false
if foo { // This always evaluates to `True`
...
}
if foo! { // This condition will now fail
...
}
The reason foo evaluated to True is because it was not unwrapped. Since its not unwrapped its just checking whether it has a value or not(true or false does not matter).
When foo was unwrapped it returned a value False hence the second if condition failed.
The println function is a special case. It automatically unwraps the variable for you. If the variable were nil, it would print nil. In other contexts, you do need to unwrap the variable yourself.

What is an optional value in Swift?

From Apple's documentation:
You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.
Why would you want to use an optional value?
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:
Things that can fail (I was expecting something but I got nothing)
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
Let's take the example of an NSError, if there isn't an error being returned you'd want to make it optional to return Nil. There's no point in assigning a value to it if there isn't an error..
var error: NSError? = nil
This also allows you to have a default value. So you can set a method a default value if the function isn't passed anything
func doesntEnterNumber(x: Int? = 5) -> Bool {
if (x == 5){
return true
} else {
return false
}
}
You can't have a variable that points to nil in Swift — there are no pointers, and no null pointers. But in an API, you often want to be able to indicate either a specific kind of value, or a lack of value — e.g. does my window have a delegate, and if so, who is it? Optionals are Swift's type-safe, memory-safe way to do this.
I made a short answer, that sums up most of the above, to clean the uncertainty that was in my head as a beginner:
Opposed to Objective-C, no variable can contain nil in Swift, so the Optional variable type was added (variables suffixed by "?"):
var aString = nil //error
The big difference is that the Optional variables don't directly store values (as a normal Obj-C variables would) they contain two states: "has a value" or "has nil":
var aString: String? = "Hello, World!"
aString = nil //correct, now it contains the state "has nil"
That being, you can check those variables in different situations:
if let myString = aString? {
println(myString)
}
else {
println("It's nil") // this will print in our case
}
By using the "!" suffix, you can also access the values wrapped in them, only if those exist. (i.e it is not nil):
let aString: String? = "Hello, World!"
// var anotherString: String = aString //error
var anotherString: String = aString!
println(anotherString) //it will print "Hello, World!"
That's why you need to use "?" and "!" and not use all of them by default. (this was my biggest bewilderment)
I also agree with the answer above: Optional type cannot be used as a boolean.
In objective C variables with no value were equal to 'nil'(it was also possible to use 'nil' values same as 0 and false), hence it was possible to use variables in conditional statements (Variables having values are same as 'TRUE' and those with no values were equal to 'FALSE').
Swift provides type safety by providing 'optional value'. i.e. It prevents errors formed from assigning variables of different types.
So in Swift, only booleans can be provided on conditional statements.
var hw = "Hello World"
Here, even-though 'hw' is a string, it can't be used in an if statement like in objective C.
//This is an error
if hw
{..}
For that it needs to be created as,
var nhw : String? = "Hello World"
//This is correct
if nhw
{..}
Optional value allows you to show absence of value. Little bit like NULL in SQL or NSNull in Objective-C. I guess this will be an improvement as you can use this even for "primitive" types.
// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l
An optional means that Swift is not entirely sure if the value corresponds to the type: for example, Int? means that Swift is not entirely sure whether the number is an Int.
To remove it, there are three methods you could employ.
1) If you are absolutely sure of the type, you can use an exclamation mark to force unwrap it, like this:
// Here is an optional variable:
var age: Int?
// Here is how you would force unwrap it:
var unwrappedAge = age!
If you do force unwrap an optional and it is equal to nil, you may encounter this crash error:
This is not necessarily safe, so here's a method that might prevent crashing in case you are not certain of the type and value:
Methods 2 and three safeguard against this problem.
2) The Implicitly Unwrapped Optional
if let unwrappedAge = age {
// continue in here
}
Note that the unwrapped type is now Int, rather than Int?.
3) The guard statement
guard let unwrappedAge = age else {
// continue in here
}
From here, you can go ahead and use the unwrapped variable. Make sure only to force unwrap (with an !), if you are sure of the type of the variable.
Good luck with your project!
When i started to learn Swift it was very difficult to realize why optional.
Lets think in this way.
Let consider a class Person which has two property name and company.
class Person: NSObject {
var name : String //Person must have a value so its no marked as optional
var companyName : String? ///Company is optional as a person can be unemployed that is nil value is possible
init(name:String,company:String?) {
self.name = name
self.companyName = company
}
}
Now lets create few objects of Person
var tom:Person = Person.init(name: "Tom", company: "Apple")//posible
var bob:Person = Person.init(name: "Bob", company:nil) // also Possible because company is marked as optional so we can give Nil
But we can not pass Nil to name
var personWithNoName:Person = Person.init(name: nil, company: nil)
Now Lets talk about why we use optional?.
Lets consider a situation where we want to add Inc after company name like apple will be apple Inc. We need to append Inc after company name and print.
print(tom.companyName+" Inc") ///Error saying optional is not unwrapped.
print(tom.companyName!+" Inc") ///Error Gone..we have forcefully unwrap it which is wrong approach..Will look in Next line
print(bob.companyName!+" Inc") ///Crash!!!because bob has no company and nil can be unwrapped.
Now lets study why optional takes into place.
if let companyString:String = bob.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
print(companyString+" Inc") //Will never executed and no crash!!!
}
Lets replace bob with tom
if let companyString:String = tom.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
print(companyString+" Inc") //Will executed and no crash!!!
}
And Congratulation! we have properly deal with optional?
So the realization points are
We will mark a variable as optional if its possible to be nil
If we want to use this variable somewhere in code compiler will
remind you that we need to check if we have proper deal with that variable
if it contain nil.
Thank you...Happy Coding
Lets Experiment with below code Playground.I Hope will clear idea what is optional and reason of using it.
var sampleString: String? ///Optional, Possible to be nil
sampleString = nil ////perfactly valid as its optional
sampleString = "some value" //Will hold the value
if let value = sampleString{ /// the sampleString is placed into value with auto force upwraped.
print(value+value) ////Sample String merged into Two
}
sampleString = nil // value is nil and the
if let value = sampleString{
print(value + value) ///Will Not execute and safe for nil checking
}
// print(sampleString! + sampleString!) //this line Will crash as + operator can not add nil
From https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html:
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
To understand deeper, read the link above.
Well...
? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.
The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.
To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, even if the property, method, or subscript you are querying returns a nonoptional value. You can use this optional return value to check whether the optional chaining call was successful (the returned optional contains a value), or did not succeed due to a nil value in the chain (the returned optional value is nil).
Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.
var defaultNil : Int? // declared variable with default nil value
println(defaultNil) >> nil
var canBeNil : Int? = 4
println(canBeNil) >> optional(4)
canBeNil = nil
println(canBeNil) >> nil
println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper
var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4
var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error
Here is basic tutorial in detail, by Apple Developer Committee: Optional Chaining
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?
You can refer to this link to get knowledge in deep: https://medium.com/#agoiabeladeyemi/optionals-in-swift-2b141f12f870
There are lots of errors which are caused by people trying to use a value which is not set, sometime this can cause a crash, in objective c trying to call the methods of a nil object reference would just be ignored, so some piece of your code not executing and the compiler or written code has no way of telling your why. An optional argument let you have variables that can never be nil, and if you try to do build it the compiler can tell you before your code has even had a chance to run, or you can decide that its appropriate for the object to be undefined, and then the compiler can tell you when you try to write something that doesn't take this into account.
In the case of calling a possible nil object you can just go
object?.doSomthing()
You have made it explicit to the compiler and any body who reads your code, that its possible object is nil and nothing will happen. Some times you have a few lines of code you only want to occur if the value exists, so you can do
if let obj = object {
obj.doSomthing()
doSomethingto(obj)
}
The two statements will only execute if object is something, simarly you may want to stop the rest of the entire block of code if its not something
guard let obj = object {
return
}
obj.doSomthing()
doSomethingto(obj)
This can be simpler to read if everything after is only applicable if object is something, another possiblity is you want to use a default value
let obj = object ?? <default-object>
obj.doSomthing()
doSomethingto(obj)
Now obj will be assigned to something even if its a default value for the type
options are useful in situation where a value may not gain a value until some event has occurred or you can use setting an option to nil as a way to say its no longer relevant or needs to be set again and everything that uses it has no point it doing anything with it until it is set, one way I like to use optionals is to tell me something has to be done or if has already been done for example
func eventFired() {
guard timer == nil else { return }
timer = scheduleTimerToCall(method, in: 60)
}
func method() {
doSomthing()
timer = nil
}
This sudo code can call eventFired many times, but it's only on the first call that a timer is scheduled, once the schedule executes, it runs some method and sets timer back to nil so another timer can be scheduled.
Once you get around your head around variables being in an undefined state you can use that for all sort of thing.
It's very simple. Optional (in Swift) means a variable/constant can be nullable. You can see that Kotlin language implements the same thing but never calls it an 'optional'. For example:
var lol: Laugh? = nil
is equivalent to this in Kotlin:
var lol: Laugh? = null
or this in Java:
#Nullable Laugh lol = null;
In the very first example, if you don't use the ?symbol in front of the object type, then you will have an error. Because the question mark means that the variable/constant can be null, therefore being called optional.
Here is an equivalent optional declaration in Swift:
var middleName: String?
This declaration creates a variable named middleName of type String. The question mark (?) after the String variable type indicates that the middleName variable can contain a value that can either be a String or nil. Anyone looking at this code immediately knows that middleName can be nil. It's self-documenting!
If you don't specify an initial value for an optional constant or variable (as shown above) the value is automatically set to nil for you. If you prefer, you can explicitly set the initial value to nil:
var middleName: String? = nil
for more detail for optional read below link
http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values