These two statements make me confused
var optionalString: String? = "Hello"
Instead we could write it
var optionalString: String = "Hello"
What's the difference between these two?
We can also do this without optional values.
var str: String = nil
str = "Hello"
Please clarify.
The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all. (It can't contain anything else, such as a Bool value or a String value. It's either an Int, or it's nothing at all.)
It is a shorthand for Nullable<int> . Nullable<T> is used to allow a value type to be set to null . Value types usually cannot be null.
The question mark ? in typescript is used in two ways: To mention that a particular variable is optional. To pre-check if a member variable is present for an object.
If double question marks are uses it is to emphasise something in return, usually from the shock of the previous thing said. For example, if I said: 'My dog just died' (sad, but used for example...) Someone may reply.
The question mark signifies that it may contain either a value, or no value at all. Without it, it cannot ever be nil
.
var str: String = "Hello"
str = nil // Error
The Question Mark (?) marks optional values. In Swift only optional values allowed to potentially be nil
.
The advantage of this feature is that it isn't necessary to check against nil
for all non optional values.
Question mark (?) is way to mark a value optional,
var optionalString: String? = "Hello"
Mean optionalString could contain a value or it could be nil.
Following is from Swift programming language book.
In an if statement, the conditional must be a Boolean expression
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.
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