For Each Key (associative array)

From SwiftAPI

Jump to: navigation, search

Contents

C++

#include <map>
#include <string>
using namespace std;
 
map<string, int> a;
a["foo"] = 10;
a["bar"] = 20;
a["baz"] = 30;
 
string x = "";
map<string, int>::iterator cur, end;
for(cur = a.begin(), end = a.end(); cur != end; cur++) {
    x = x + cur->first;
}
 
// x == "barbazfoo"

Java

import java.util.Map;
import java.util.HashMap;
 
Map<String, Integer> a = new HashMap<String, Integer>();
a.put("foo", 10);
a.put("bar", 20);
a.put("baz", 30);
 
String x = "";
for(String k : a.keySet()) {
    x = x + k;
}
// x == "bazfoobar"

JavaScript

Mozilla

var a = {'foo': 10, 'bar': 20, 'baz': 30};
var x = '';
for (var k in a) {
    x = x + k;
}
// x == "foobarbaz"

Objective-C

developer.apple.com

for ( key in dictionary ) { statements }
NSDictionary *a = @{@"foo": @10, @"bar": @20, @"baz": @30};
NSMutableString *x = [NSMutableString string];
for (NSString *k in a) {
  [x appendString:k];
}
// x == @"foobarbaz"

Perl

%a = ('foo' => 10, 'bar' => 20, 'baz' => 30);
$x = '';
foreach $k (keys(%a)) {
    $x = $x . $k;
}
# $x == "barbazfoo"
 
# alternately:
while ($k = each(%a)) {
    $x = $x . $k;
}
# $x == "barbazfoo"

PHP

$a = array('foo' => 10, 'bar' => 20, 'baz' => 30);
$x = '';
foreach(array_keys($a) as $k) {
    $x = $x . $k;
}
// $x == "foobarbaz"

Python

a = {'foo': 10, 'bar': 20, 'baz': 30}
x = ''
for k in a:
    x = x + k
# x == "bazfoobar"

Ruby

a = {"foo" => 10, "bar" => 20, "baz" => 30}
x = ''
a.each_key do |k|
    x = x + k
end
# x == "bazfoobar"

Swift

let a = ["foo": 10, "bar": 20, "baz": 30]
var x = ""
for k in a.keys {
    x = x + k
}
// x == "barbazfoo"
Personal tools