Question mark(?) after data type

i0S Swift Issue

Question or problem in the Swift programming language:

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.

How to solve the problem:

Solution 1:

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

Solution 2:

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.

Solution 3:

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.

Hope this helps!