0

I'm new to Swift. Could someone please tell me what "??" stands for and what is its function in the context of

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

I have included the complete code below:

struct Item{
    var price: Int
    var count: Int
}

class VendingMachine {
    var inventory = [
    "Candy bar": Item(price: 12, count: 7),
    "Chips": Item(price: 10, count: 4),
    "Pretzels": Item(price: 7, count: 11)
    ]
    var coinsDeposited = 0
    func dispenseSnack(snack: String){
        print("dispensing \(snack)")
    }

    func vend(itemNamed name: String) throws {
        guard var item = inventory[name] else {
            throw VendingMachineError.InvalidSelection
        }

        guard item.count > 0 else {
            throw VendingMachineError.OutOfStock
        }

        guard item.price <= coinsDeposited else {
            throw VendingMachineError.InsufficientFunds(coinsNeeded: item.price - coinsDeposited)
        }

        coinsDeposited -= item.price
        --item.count
        inventory[name] = item
        dispenseSnack(name)
    }
}

let favoriteSnacks = [
    "Alice": "Chips",
    "Bob": "Licorice",
    "Eve": "Pretzels",
]

func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
    let snackName = favoriteSnacks[person] ?? "Candy bar"
    try vendingMachine.vend(itemNamed: snackName)
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 1
    it is a default value in case there is no favorite – Leo Dabus Feb 11 '16 at 05:28
  • 2
    See http://nshipster.com/swift-operators/ - and search for "swift operators"; this search 'trick' works for just about any language. By isolating the type of symbol ("operator"), and then using a localized (in page) search.. – user2864740 Feb 11 '16 at 05:28
  • 1
    it is called nil coalescing operator – Leo Dabus Feb 11 '16 at 05:29
  • Possible duplicate of [?? operator in Swift](https://stackoverflow.com/questions/30772063/operator-in-swift) – Cristik Feb 06 '19 at 06:02

5 Answers5

4

Its used to checking nil, if your value will be nil, you will assign default value.

let favoriteSnacks = [
    "Alice": "Chips",
    "Bob": "Licorice",
    "Eve": "Pretzels",
]

from your code,

suppose person = "Eve"

let snackName = favoriteSnacks["Eve"] ?? "Candy bar"

it will first try to find value from dictionary, i.e. favoriteSnacks["Eve"] will give you value "Pretzels".

so it will assign value Pretzels to snackName variable.

suppose person = "Allen"

let snackName = favoriteSnacks["Allen"] ?? "Candy bar"

it will first try to find value from dictionary, i.e. favoriteSnacks["Allen"] will give you value nil.

In this case it will assign defalut value "Candy bar" to your variable snackName.

Hitendra Solanki
  • 4,871
  • 2
  • 22
  • 29
2

Let me please assume here based on its meaning in other languages:

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

?? checks if the value of favoriteSnacks[person] is null. If it is NOT then the value of favoriteSnacks[person] will be assigned to snackName. If the value of favoriteSnacks[person] is null then "Candy bar" will be assigned to snackName.

It is used for having a default value in case favoriteSnacks[person] comes null.

alexandergs
  • 182
  • 2
  • 12
2

Its the Nil Coalescing Operator basically giving a default for when the value does not exist.

see also Providing a default value for an Optional in Swift?

Community
  • 1
  • 1
Timothy Pratley
  • 10,586
  • 3
  • 34
  • 63
  • don't provide link, instead of this thing you can copy paste the text from that link and paste in answer, because there can be change that webpage will be removed. – Hitendra Solanki Feb 11 '16 at 05:44
0

Ex. if you get only 5 keys and values in dictionary, but some time getting nil key or value, then error will be come for nil value. So, here solution for that,

 var strName = jsonObjectName ?? "Unknown"
 var intAge = jsonObjectAge ?? 25

it means, if jsonObjectName is nil then automatically "Unknown" will be set to strName.

Note: default value provided by "?? value"

Deepak Tagadiya
  • 2,187
  • 15
  • 28
0

Simply explained,

let value = x ?? y

Is similar to writing,

let value = x != nil ? x! : y

It checks if x contains nil, if it doesn't then it force unwraps it, otherwise returns y in the above case.

Mahesh
  • 1,472
  • 1
  • 9
  • 16