In Swift programming I found some question marks with objects.
var window: UIWindow?
Can anybody explain the use of it?
Double question mark is a nil-coalescing operator. In plain terms, it is just a shorthand for saying != nil . First it checks if the the return value is nil, if it is indeed nil, then the left value is presented, and if it is nil then the right value is presented.
A means added to source control, but not modified. M means it is added to source control and is modified. Also, if you see the question mark against a file that you know is tracked, and the Source Control->Refresh Status menu option doesn't change anything, try just quitting and restarting Xcode.
Answer and Explanation: The usage of multiple question marks is not punctually correct; however, double question marks are often used to emphasize the question that precedes it.
The bang or exclamation mark hints at potential danger. If you use an exclamation mark in Swift, you are about to perform an operation that can backfire. You are about to perform a dangerous operation and are doing so at your own risk. That is the meaning of the exclamation mark in Swift.
You can use
if
andlet
together to work with values that might be missing. These values are represented asoptionals
. Anoptional
value either contains a value or containsnil
to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value asoptional
.If the optional value is
nil
, the conditional isfalse
and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant afterlet
, 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.
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