JW.ZG
JW.ZG

Reputation: 611

Why can I declare a variable without writing optional mark?

First of all, I believe my question is different with those questions about "what is optional in swift". Because I am asking why I can do this, not what is this.

I am new to swift. When I learn this fabulous language tonight, I got a problem that I never saw this mark-"?" in a programming language. And I searched it for a while. I know what optional binding is now.

But now I got a new question. When I want to declare a variable that is not optional. I can write this syntax:

var friend: String

But I can't write:

var friend: String = nil

To declare a variable that is nil I can only use optional:

var friend: String? = nil

Let's see the first piece of code. When the new variable friend just be declared, its value is nil, right? Because I didn't assign any value to it. But according to the definition of optional, like the second and the third pieces of code, we can't assign nil to non-optional variables.

So my question is why I can declare a variable without optional mark but has no initial value. This question may be simple, but I really don't know why it happens.

Thanks in advance!

Upvotes: 15

Views: 10883

Answers (2)

Dan Beaulieu
Dan Beaulieu

Reputation: 19994

The first value you set is an uninitialized variable with the type of string.

A very common pattern in programming is to have an operation that might or might not return a value. In some languages, like javascript, when coming across a null value our program continues to operate just fine as long as our program is not dependent on that value to continue. In other languages, like java for example, a null value can cause a NullPointerException and crash our program.

Swift's solution to this problem is optionals. By default if we define a variable without a value, the compiler will complain. So, in order to declare a value that may or may not have a value at runtime, we need to add a ? which is known as “wrapping our values in an optional”. This is because we are indeed literally wrapping our value in Swifts optional type, thus giving it value. To get a better picture as to whats going on, we can look at how Swifts Optional enum.

enum Optional<T> {
    case None // has no value
    case Some(T) // has some value
} 

Upvotes: 0

Marc Khadpe
Marc Khadpe

Reputation: 2002

Swift allows you to declare a non-optional variable or constant without initializing it in the declaration, but you will have to assign it a value before using it. The value of the variable or constant is not nil (non-optionals can never be nil)--it simply has no defined value. Basically you are saying you will give it a value later, possibly based on the result of a computation or an if statement.

Swift will give you a compile-time error if you try to use a non-optional variable or constant without first assigning a value to it.

Upvotes: 16

Related Questions