Swift optional variable assignment with default value (double question marks)
The nil-coalescing operator a ?? b
is a shortcut for
a != nil ? a! : b
it returns either the left operand unwrapped or the right operand. So the type of foo
is String
and the second line should be
var bar = some_func(string: foo)
without the exclamation mark because foo
is not an optional and can't be unwrapped.
(If you change the first line to
let foo: String? = dict["key"] as? String ?? "empty"
then the result of the right hand side is wrapped into an optional string again, and needs
to be unwrapped in the second line. It makes the error go away, but this is probably not what you want.)
Providing a default value for an Optional in Swift?
Update
Apple has now added a coalescing operator:
var unwrappedValue = optionalValue ?? defaultValue
The ternary operator is your friend in this case
var unwrappedValue = optionalValue ? optionalValue! : defaultValue
You could also provide your own extension for the Optional enum:
extension Optional {
func or(defaultValue: T) -> T {
switch(self) {
case .None:
return defaultValue
case .Some(let value):
return value
}
}
}
Then you can just do:
optionalValue.or(defaultValue)
However, I recommend sticking to the ternary operator as other developers will understand that much more quickly without having to investigate the or
method
Note: I started a module to add common helpers like this or
on Optional
to swift.
What does ?? mean on a variable declaration in Swift case let pattern matching?
In the context of pattern matching, x?
is the “optional pattern” and equivalent to .some(x)
. Consequently, case x??
is a “double optional pattern” and equivalent to .some(.some(x))
.
It is used here because UIApplication.shared.delegate?.window
evaluates to a “double optional” UIWindow??
, compare Why is main window of type double optional?.
Therefore
if case let presentationAnchor?? = UIApplication.shared.delegate?.window
matches the case that UIApplication.shared.delegate
is not nil and the delegate implements the (optional) window
property. In that case presentationAnchor
is bound to the “doubly unwrapped” UIWindow
.
See also Optional Pattern in the Swift reference:
An optional pattern matches values wrapped in a
some(Wrapped)
case of anOptional<Wrapped>
enumeration. Optional patterns consist of an identifier pattern followed immediately by a question mark and appear in the same places as enumeration case patterns.
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
Optional value in swift 3 Optimised way
You seem to have asked two different questions here. The first one regarding doubles have already been answered by adev. I will answer the second one, which is:
if i assign nil value to variable then it should remain with its default value without writing this Optional chaining ?? "abc" in constructor
If you want to do this then it means that the variable shouldn't be optional at all, as nil
isn't one of its valid values. Make the variable a non-optional type and give it a default value.
class TestingModel{
var id : String = ""
var name : String = "abc"
var price : Double = 0.00
var uniqueId : Int = 1
}
You can't really avoid using ??
in the constructor because of the nature of dictionaries. They will always return a nil
value if the key does not exist. You have to check it. It does not make sense even if this is possible anyway. Imagine something like this:
someVariable = nil // someVariable is now 0
This is extremely confusing. someVariable
is 0, even though it appears that nil
is assigned to it.
A workaround will be to add a dictionary extension. Something like this:
extension Dictionary {
func value(forKey key: Key, defaultValue: Value) -> Value {
return self[key] ?? defaultValue
}
}
But I still recommend that you use ??
instead.
How can I safety unwrap an optional with a default value using `coalescing unwrapping` - Not workig - Swift
You can unwrap the access of the array and the conversion to Double
let pounds = Double(arrayOfStrings.first ?? "0") ?? 0.0
Nil coalescing operator in swift returns a weird result
There's a lot going on here:
a
overflows, becaue128
is larger than the maximum value that can be stored in anInt8
(Int8.max
=127
), thus it'll returnnil
.This
nil
, a.k.a.Optional.None
is of typeOptional<Int8>
is not the type specified by the type annotation ofa
(Int8??
, a.k.a.Optional<Optional<Int8>>
), so it's wrapped in another optional, becomingOptional.Some(Optional.None)
, which is now the correct type.nilCoalescing()
doesn't return anything. (Which actually means it returns()
, a.k.a.Void
)Don't do this explicit
nil
check and force unwrap (!
):a != nil ? a! : b
. Use??
instead:a ?? b
What exactly are you trying to do here?
Why can I declare a variable without writing optional mark?
Swift allows you to declare a non-optional variable or constant without initializing it in the declaration, but you will have to assign it a value before using it. The value of the variable or constant is not nil (non-optionals can never be nil)--it simply has no defined value. Basically you are saying you will give it a value later, possibly based on the result of a computation or an if statement.
Swift will give you a compile-time error if you try to use a non-optional variable or constant without first assigning a value to it.
Related Topics
Swiftui - Navigation View Opening with Back Button and Half Grey Screen/Weird Behavior
Swift: Call Self Method Inside Init
Deleterowsatindexpaths Crashing
Nsurl from String Gets Truncated, Dots on the Uivideoeditorcontroller's Video Path Swift 2 iOS 8
How to Have Either or Wherefields for Firestore Query
C++ Dylib in Swift Project - Undefined Symbols for Function Exposed in Dylib
Use Huge Numbers in Apple Swift
Swiftui How to Programatically Adjust Spacing Between Images and Text
How to Loop All Firebase Children at Once in the Same Loop
Autoscrolling Infinite Effect in .Linear Type of Icarousel in Swift
Can Openssl Be Bundled for Wget Wrapper App to Reference in Xcode Project
Why Does Classa Adopting Protocolb Not Satisfy the Protocolb Requirement
How to Pass a Local Function to Another Object During Init
How to Deal with Commas When Writing Objects to CSV in Swift
How Assistant Model Works in Swift
How to Create an Operator to Implement Error Chaining