Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question mark(?) after data type [duplicate]

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.

like image 675
Mani Avatar asked Jun 03 '14 07:06

Mani


People also ask

What does the question mark (?) Indicate a particular property is?

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.)

What does a question mark after a type mean?

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.

What is question mark in typescript?

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.

What does a double question mark mean?

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.


3 Answers

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
like image 176
Tom van der Woerdt Avatar answered Dec 03 '22 23:12

Tom van der Woerdt


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.

like image 36
Ben-G Avatar answered Dec 04 '22 00:12

Ben-G


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.

like image 27
Waruna Avatar answered Dec 04 '22 00:12

Waruna