What the meaning of question mark ‘?’ in swift?

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 the optional value is nil, the conditional is false and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/pk/jEUH0.l

For Example:

var optionalString: String? = "Hello"
optionalString == nil

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

In this code, the output would be Hello! John Appleseed. And if we set the value of optionalName as nil. The if conditional result would be false and code inside that if would get skipped.

Leave a Comment

tech