Associative Array Remove Value

From SwiftAPI

Jump to: navigation, search

Contents

C++

msdn

map<string, int> a;
a["test"] = 4;
a["foo"] = 2;
a["bar"] = 1;
a.erase("foo");

C#

using System.Collections.Generic;
 
Dictionary<string, int> a = new Dictionary<string, int>() { { "test", 4 }, { "foo", 2 }, { "bar", 1 } };
a.Remove("foo");

Java

import java.util.Map;
import java.util.HashMap;
 
Map<String, Integer> a = new HashMap<String, Integer>();
a.put("test", 4);
a.put("foo", 2);
a.put("bar", 1);
a.remove("foo");
// a == { "test": 4, "bar": 1 }

JavaScript

Mozilla

var a = { test: 4, foo: 2, bar: 1 };
delete a['foo'];
// a == { test: 4, bar: 1 }

Objective-C

developer.apple.com

- (void)removeObjectForKey:(id)aKey
NSMutableDictionary *a = [NSMutableDictionary dictionaryWithObjectsAndKeys:@4, @"test",
                                                                           @2, @"foo",
                                                                           @1, @"bar", nil];
[a removeObjectForKey:@"foo"];
// a == { @"test": 4, @"bar": 1 }

Perl

%a = ("test", 4, "foo", 2, "bar", 1);
delete $a{"foo"};
# %a == ("test", 4, "bar", 1)

Note: Do not confuse the above code with

unset $a{"foo"};

unset() merely sets the value at key "foo" to undef. The key still exists, as can be tested with exists(). Always use delete() to remove a key from a hash.

PHP

php.net

$a = array('test' => 4, 'foo' => 2, 'bar' => 1);
unset($a['foo']);
// $a == array('test' => 4, 'bar' => 2);

Python

a = {"test": 4, "foo": 2, "bar": 1}
del a["foo"]
# a == {"test": 4, "bar": 1}

Ruby

ruby-doc.org

hsh.delete(key) => value
hsh.delete(key) {| key | block } => value
a = {"test" => 4, "foo" => 2, "bar" => 1}
a.delete("foo")
# a == {"test" => 4, "bar" => 1}

Swift

var a = ["test": 4, "foo": 2, "bar": 1]
a["foo"] = nil
// a == ["test": 4, "bar": 1]
Personal tools