Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 993 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
?? operator in Swift

#1
In the "The Swift Programming Language" book (page 599), I came across this code snippet that kind of confused me. It went like this:

func buyFavoriteSnack(person:String) throws {
let snackName = favoriteSnacks[person] ?? "Candy Bar"
try vend(itemName:snackName)
}

Its explanation was:

> The buyFavoriteSnack(_:) function looks up the given person's favorite snack and tries to buy it for them. If they don't have a favorite snack listed, it tries to buy a candy bar. If they...

How can this explanation map to the "??" operator in the code given. When should/can we use this syntax in our own code?
Reply

#2
It is "nil coalescing operator" (also called "default operator"). `a ?? b` is value of `a` (i.e. `a!`), unless `a` is `nil`, in which case it yields `b`. I.e. if `favouriteSnacks[person]` is missing, return assign `"Candy Bar"` in its stead.
Reply

#3
The nil-coalescing operator `a ?? b` is a shortcut for `a != nil ? a! : b`
Reply

#4
let something = a ?? b

means

let something = a != nil ? a! : b
Reply

#5
This:

let snackName = favoriteSnacks[person] ?? "Candy Bar"

Is equals this:

if favoriteSnacks[person] != nil {
let snackName = favoriteSnacks[person]
} else {
let snackName = "Candy Bar"
}

Explaining in words, if the `let` statement fail to grab `person` from `favoriteSnacks` it will assigned Candy Bar to the `snackName`
Reply

#6
One addition to @Icaro's answer you can declare values without initialize them. In my opinion this is better:

func buyFavoriteSnack(person:String) throws {
// let snackName = favoriteSnacks[person] ?? "Candy Bar"
let snackName: String

if let favoriteSnackName = favoriteSnacks[person] {
snackName = favoriteSnackName
} else {
snackName = "Candy Bar"
}

try vend(itemName:snackName)
}
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through