Associative Array Get Value

From SwiftAPI

Jump to: navigation, search

Contents

C++

#include <map>
#include <string>
using namespace std;
 
// Caution: the indexing operator will insert a (default) value when the key does not already exist.
// Note: this won't work on a const map
map<string, int> a;
a["test"] = 5;
int x = a["test"];
// x == 5
 
// This method will work on a const map; and will not insert a new value. If the key is not found, find()
// returns the .end() iterator of the map, so you should probably check that before dereferencing it.
const map<string, int> b = a;
int x = *a.find("test");
// x == 5

C#

Dictionary<string, int> a = new Dictionary<string, int>() { { "test", 5 } };
int x = a["test"];
// x == 5

Java

import java.util.*;
 
Map<String, Integer> a = new HashMap<String, Integer>();
a.put("test", 5);
Integer x = a.get("test");
// x == 5

JavaScript

Mozilla

var a = { test: 5 };
var x = a["test"]; // or equivalently: var x = a.test
// x == 5

Objective-C

developer.apple.com

NSDictionary *a = @{@"test": @5};
NSNumber *x = a[@"test"];
// x == 5

or: developer.apple.com

- (id)objectForKey:(id)aKey
NSDictionary *a = @{@"test": @5};
NSNumber *x = [a objectForKey:@"test"];
// x == 5

Perl

%a = ("test" => 5);
$x = $a{"test"};
# $x == 5

PHP

$a = array('test' => 5);
$x = $a['test'];
// $x == 5

Python

a = {'test': 5 }
x = a['test']
# x == 5

Ruby

a = {'test' => 5 }
x = a['test']
# x == 5

Swift

let a = ["test": 5]
let x = a["test"]
// x == Optional(5)
Personal tools