Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 928
JW.ZG Avatar asked Dec 19 '15 05:12

JW.ZG


People also ask

Can you declare a variable without a data type?

All variables in the Java language must have a data type. A variable's type determines the values that the variable can have and the operations that can be performed on it. For example, the declaration int count declares that count is an integer ( int ).

Can you declare a variable without assigning a value?

Still, this is a common question asked by many programmers that can we declare any variable without any value? The answer is: "Yes! We can declare such type of variable". To declare a variable without any variable, just assign None.

How do you declare a variable without a type in Python?

Use the None Keyword to Declare a Variable Without Value in Python. Python is dynamic, so one does not require to declare variables, and they exist automatically in the first scope where they are assigned. Only a regular assignment statement is required. The None is a special object of type NoneType .


1 Answers

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.

like image 95
Marc Khadpe Avatar answered Oct 25 '22 12:10

Marc Khadpe