What is the ?? operator? [duplicate] - swift

This question already has answers here:
?? operator in Swift
(5 answers)
Closed 4 years ago.
What is the ?? operator
The Swift Programming Language (Swift 4.1)
I was reading the book The Swift Programming Language (Swift 4.1) by apple and I got to a part where it talks about the ?? operator:
Expert
Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 4.1).” iBooks. https://itunes.apple.com/us/book/the-swift-programming-language-swift-4-1/id881256329?mt=11
Problem
Optional Values
In the expert it says that the ?? operator is for a optional value I was wondering what it does for a Optional Value.
What it does
So the other thing I wanted to know is what does the ?? operator do.

Nil-Coalescing Operator (??)
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.
?? - indicates default value assignment, when your variable has a nil value.
Consider following example:
var int a = nil // var a with nil value assignment
var int b = a ?? 1 // first trying to get value from a. If var a has nil then it will try assign value 1.
print("b = \(b)")
result: b = 1

Related

Optionals in Swift - not assigning default value for optionals [duplicate]

This question already has answers here:
Why optional constant does not automatically have a default value of nil [duplicate]
(2 answers)
Constant unassigned optional will not be nil by default
(1 answer)
Closed 5 years ago.
let company : String? // = nil
if company == nil {
var newCompany = company ?? "apple"
}
In this code identifier company we need to assign as
let company : String? = nil
but apple documentation is telling that no need for assigning nil value
You declared a constant without a value and without an initializer that can change it, which is nonsensical. The compiler, therefore, warns you that you should initialize the constant.
Change let to var and your code will work fine.

Nil coalescing operator in swift returns a weird result

Could anyone tell me why Xcode's Playground returns nil if I put double question mark instead of single question mark for variable a?
Due to overflow result must be 64, not nil.
Swift version 2.2,
Xcode version 7.3.1,
OS X version 10.11.6
import Cocoa
var b: Int8
var c: String? = "128"
var a: Int8?? = Int8(c!)
b = 64
func nilCoalescing() {
a != nil ? a! : b
}
nilCoalescing()
128 overflows when converted to Int8 so it is stored as nil.
There's a lot going on here:
a overflows, becaue 128 is larger than the maximum value that can be stored in an Int8 (Int8.max = 127), thus it'll return nil.
This nil, a.k.a. Optional.None is of type Optional<Int8> is not the type specified by the type annotation of a (Int8??, a.k.a. Optional<Optional<Int8>>), so it's wrapped in another optional, becoming Optional.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?

Swift shorthand to access property versus default value [duplicate]

This question already has answers here:
Providing a default value for an Optional in Swift?
(5 answers)
Closed 7 years ago.
Does Swift have a shorthand syntax for substituting default values when trying to access properties on an optional? For example:
let value = anOptional != nil ? anOptional.value : defaultValue
This is not a question about the simple use of the ?? coalescing operator, but a question about a shorthand syntax for assigning from a property on a non-nil optional.
You can do this let value = anOptional ?? defaultValue

Why can I use a constant initialization as if-condition? [duplicate]

This question already has answers here:
How is Swift `if let` evaluated?
(5 answers)
Closed 7 years ago.
While reading the official Apple Guide I found this
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello \(name)"
}
There is a constant declaration and assignment where I — as a beginner — expected an expression returning a boolean. But the condition of this if statement seems to get true as the value, because the code inside the parentheses is being executed.
Does the initialization of a constant return a boolean value or something that a if statement can use as a condition?
This is called Optional Binding. Quoting from the Basics -> Optionals -> Optional Binding section of the Swift Language Guide.
You use optional binding to find out whether an optional contains a
value, and if so, to make that value available as a temporary constant
or variable. Optional binding can be used with if and while statements
to check for a value inside an optional, and to extract that value
into a constant or variable, as part of a single action.
What this if let construct is doing is checking if someOptional is exists. If it isn't nil/.None then it "binds" the Optional value to a constant.
if let constantName = someOptional {
...
}
This can be thought of as:
if someOptional != nil {
let constantName = someOptional!
....
}

What does an exclamation mark in a property in Swift language? [duplicate]

This question already has answers here:
What does an exclamation mark mean in the Swift language?
(23 answers)
Swift variable decorations with "?" (question mark) and "!" (exclamation mark)
(1 answer)
Closed 8 years ago.
There are three way to declare a property in Swift:
var optStr: String?
var normStr: String = "normStr"
var exactStr: String!
The first one is property with an optional type, a type that can contain either nil or the String in our case. The second one is a property that always contain the String. It should be initialized in init or in the declaration.
But what about the third way?
var exactStr: String!
I made some experiments in the playground, and it turned out that a function that takes type? can take both type, type? and type! variables as an argument:
var optStr: String?
var normStr: String
var forcedStr: String!
func printStr(str: String?) {
println("str: \(str)")
}
printStr(optStr) //prints: "str: nil"
//printStr(normStr) //doesn't compile as not initialized
printStr(forcedStr) //prints: "str: nil"
optStr = "optStr"; normStr = "normStr"; forcedStr = "forcedStr"
printStr(optStr) //prints "str: optStr"
printStr(normStr) //prints "str: normStr"
printStr(forcedStr) //prints "str: forcedStr"
So why and when should I use type!?
Update: this is not a duplicate of What does an exclamation mark mean in the Swift language?. I'm not asking about unwrapping a variable: I'm asking about declaring a property with an exclamation point (Type!).
It's a variable of type "implicitly-unwrapped optional String". Essentially, every access of implicitStr is treated as if it were written implicitStr! (thus unwrapping the value).
This, of course, will cause a crash if the value is nil. You can still test the implicit optional via if implicitStr != nil, or use it in optional chaining as var foo = implicitStr?.uppercaseString. So you can still use it just as safely as a normal optional; it's just biased toward the case where the value is not nil.
Implicitly-unwrapped optionals are quite useful in cases where the value may not be present at initialization, but are set early and unlikely to become nil again. (For example, a variable you set in -awakeFromNib might reasonably be an implicitly-unwrapped optional.)
Further, since Objective-C methods can return both nil and object types, their return values cannot be modeled as non-optional. To avoid requiring liberal use of forced unwrapping whenever dealing with Cocoa APIs, though, the parameters and return types of Cocoa APIs are usually represented as implicitly-unwrapped optionals.