What the meaning of question 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.
Swift files in Xcode have Question Mark (?)
The question mark means that the file is not under version control, it doesn't mean that it has been deleted. You can use the command git add -A
to add all files in the directory to your version control. This SO question lists all the Xcode version control symbols, here they are.
U: Working file was updated
G: Changes on the repo were automatically merged into the working copy
M: Working copy is modified
C: This file conflicts with the version in the repo
?: This file is not under version control
!: This file is under version control but is missing or incomplete
A: This file will be added to version control (after commit)
A+: This file will be moved (after commit)
D: This file will be deleted (after commit)
S: This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a branch
I: Ignored
X: External definition
~: Type changed
R: Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place.
L : Item is locked
E: Item existed, as it would have been created, by an svn update.
what's the purpose of double question mark in swift
It is called nil coalescing operator. If highs
is not nil
than it is unwrapped and the value returned. If it is nil then [ChartHighlight]()
returned. It is a way to give a default value when an optional is nil
.
What does the double question mark means at the end of the type?
Double??
is shorthand notation for Optional<Optional<Double>>
, which is simply a nested Optional
. Optional
is a generic enum
, whose Wrapped
value can actually be another Optional
and hence you can create nested Optional
s.
let optional = Optional.some(2)
let nestedOptional = Optional.some(optional)
The type of nestedOptional
here is Int??
.
For your specific example, item.first
is Double??
, since item
itself is of type [Double?]
and Array.first
also returns an Optional
, hence you get a nested Optional
.
Your compactMap
call on data
achieves nothing, since you call it on the outer-array, whose elements are non-optional arrays themselves. To filter out the nil
elements from the nested arrays, you need to map
over data
and then call compactMap
inside the map
.
let nonNilData = data.map { $0.compactMap { $0 } } // [[100, 35.6], [110, 42.56], [120, 48.4], [200]]
What is the meaning of ?? in swift?
Nil-Coalescing Operator
It's kind of a short form of this. (Means you can assign default value nil
or any other value if something["something"]
is nil
or optional)
let val = (something["something"] as? String) != nil ? (something["something"] as! String) : "default value"
The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.
The nil-coalescing operator is shorthand for the code below:
a != nil ? a! : b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.
If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.
The example below uses the nil-coalescing operator to choose between a default color name and an optional user-defined color name:
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"
See section Nil-Coalescing Operator here
Swift variable decorations with ? (question mark) and ! (exclamation mark)
In a type declaration the !
is similar to the ?
. Both are an optional, but the !
is an "implicitly unwrapped" optional, meaning that you do not have to unwrap it to access the value (but it can still be nil).
This is basically the behavior we already had in objective-c. A value can be nil, and you have to check for it, but you can also just access the value directly as if it wasn't an optional (with the important difference that if you don't check for nil you'll get a runtime error)
// Cannot be nil
var x: Int = 1
// The type here is not "Int", it's "Optional Int"
var y: Int? = 2
// The type here is "Implicitly Unwrapped Optional Int"
var z: Int! = 3
Usage:
// you can add x and z
x + z == 4
// ...but not x and y, because y needs to be unwrapped
x + y // error
// to add x and y you need to do:
x + y!
// but you *should* do this:
if let y_val = y {
x + y_val
}
swift if let statement with as?,but why use question mark?
Your code:
if let foo = object as? String
breaks into two significant parts: object as? String
and if let
.
The first is a downcast which allows for failure by producing an optional type (String?
here). From The Swift Programming Language (Swift 3.1): Typecasting:
Use the conditional form of the type cast operator (
as?
) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will benil
if the downcast was not possible. This enables you to check for a successful downcast.
The second, if let
, is an optional binding which unwraps an optional, the body of the if let
is only executed if the optional value being unwrapped is not nil
and with the bound variable being bound to the unwrapped value. See Optional Binding in The Swift Programming Language (Swift 3.1): Basics.
So your sense that something is happening twice here is correct. The as?
cast may fail and produce a nil
optional value, the if let
will test that optional value for nil
. We can only hope that the compiler handles the combination of if let
and as?
together and no unneccesary optionals are actually created and destroyed by the implementation.
HTH
Question mark(?) after data type
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
Related Topics
Playing Video Inline in Ionic/Phonegap (Webkit-Playsinline Not Working)
Afnetworking - Do Not Cache Response
Swift Calculate Md5 Checksum for Large Files
Swift Images Change to Wrong Images While Scrolling After Async Image Loading to a Uitableviewcell
Xcode 6.3.2 Can't Run on Osx 10.11 El Capitan Developer Preview 3
Encryption with Rsa Public Key on iOS
How Big Can the Payload Be When Sending Data via Watchconnectivity
Best Way to Save and Retrieve Uicolors to Core Data
Set Delegates to Nil Under Arc
Detect and Use Optional External C Library at Runtime in Objective-C
How to Write Application Logs to File and Get Them
Generating Custom Thumbnail from Alassetrepresentation
Swift: Natively Detect If App Has Crashed
Easiest Way of Getting Reverse Geocoded Current Location from iOS