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!
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 ).
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With