Skip to content

Instantly share code, notes, and snippets.

@DeveloperMaris
Created February 16, 2023 06:57
Show Gist options
  • Save DeveloperMaris/96d67a4a63e9e234380bead5eddcdfa5 to your computer and use it in GitHub Desktop.
Save DeveloperMaris/96d67a4a63e9e234380bead5eddcdfa5 to your computer and use it in GitHub Desktop.
How to set dictionary values to nil
//
// main.swift
// RemoveFromDictionary
//
// Created by Maris Lagzdins on 16/02/2023.
//
import Foundation
var oscarWinners = [
"Best Actor": "Will Smith",
"Best Actress": "Jessica Chastain",
"Best Picture": "CODA",
"Best Director": nil
]
print(oscarWinners)
/*
[
"Best Actress": Optional("Jessica Chastain"),
"Best Picture": Optional("CODA"),
"Best Actor": Optional("Will Smith"),
"Best Director": nil
]
*/
// Setting the value as `nil` will remove the value with it's key from the dictionary.
oscarWinners["Best Picture"] = nil
print(oscarWinners)
/*
[
"Best Actress": Optional("Jessica Chastain"),
"Best Actor": Optional("Will Smith"),
"Best Director": nil
]
*/
// Updating the value as `nil` will only change the value but will not remove the key from the dictionary.
oscarWinners.updateValue(nil, forKey: "Best Actor")
print(oscarWinners)
/*
[
"Best Actress": Optional("Jessica Chastain"),
"Best Actor": nil,
"Best Director": nil
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment