Associative Array Set

From SwiftAPI

Jump to: navigation, search

Contents

C++

#include <string>
#include <map>
#include <utility>
using namespace std;
 
map<string, int> a;
a["test"] = 5;
 
// If you want more information, you can do the following (however, this only works if the key did not already exist):
pair<map<string, int>::iterator, bool> result = a.insert(make_pair("test", 5));
pair.second; // this Boolean tells you if the insertion succeeded (i.e. if an element with that key did not exist)
pair.first; // this iterator points to the pair that either you just inserted, or already existed in the map

C#

[] operator

using System.Collections.Generic;
 
Dictionary<string, int> a = new Dictionary<string, int>();
a["test"] = 5;

Add

using System.Collections.Generic;
 
Dictionary<string, int> a = new Dictionary<string, int>();
a.Add("test", 5);

Java

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

JavaScript

var a = {};
a["test"] = 5;
// a == {"test": 5}

Objective-C

NSMutableDictionary *a = [NSMutableDictionary dictionary];
a[@"test"] = @5;
// a == {@"test": 5}

or: developer.apple.com

- (void)setObject:(id)anObject forKey:(id)aKey
NSMutableDictionary *a = [NSMutableDictionary dictionary];
[a setObject:@5 forKey:@"test"];
// a == {@"test": 5}

Perl

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

PHP

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

Python

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

Ruby

a = {}
a["test"] = 5
# a == {"test" => 5}

Swift

var a : [String : Int] = [:]
a["test"] = 5
// a == ["test": 5]
Personal tools