For Each Key Value (associative array)
From SwiftAPI
Contents |
C++
#include <map> using namespace std; map<string, int> a; a["foo"] = 1; a["bar"] = 3; a["baz"] = 42; int s = 0; for (map<string, int>::iterator iter = a.begin(); iter != a.end(); iter++) { string k = iter->first(); int v = iter->second(); s = s + v; } // s == 46
Java
import java.util.Map; import java.util.HashMap; Map<String, Integer> a = new HashMap<String, Integer>(); a.put("foo", 1); a.put("bar", 3); a.put("baz", 42); int s = 0; for (Map.Entry<String, Integer> entry : a.entrySet()) { String k = e.getKey(); Integer v = e.getValue(); s = s + v; } // s == 46
JavaScript
jQuery
var a = {"foo": 1, "bar": 3, "baz": 42}; var s = 0; $.each(a, function(k, v) { s = s + v; }); // s == 46
Objective-C
- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block
NSDictionary *a = @{@"foo": @1, @"bar": @3, @"baz": @42}; __block int s = 0; [a enumerateKeysAndObjectsUsingBlock:^(id key, NSNumber *v, BOOL *stop) { s += v.intValue; }]; // s == 46
Perl
%a = ('foo' => 1, 'bar' => 3, 'baz' => 42); $s = 0; while (($k, $v) = each %a) { $s = $s + $v; } # $s == 46
Be careful when using each(), however, because it uses a global iterator associated with the hash. If you call keys() or values() on the hash in the middle of the loop, the each() iterator will be reset to the beginning. If you call each() on the hash somewhere in the middle of the loop, it will skip over elements for the "outer" each(). Only use each() if you are sure that the code inside the loop will not call keys(), values(), or each().
PHP
$a = array('foo' => 1, 'bar' => 3, 'baz' => 42); $s = 0; foreach($a as $k => $v) { $s = $s + $v; } // $s == 46
Python
a = {"foo": 1, "bar": 3, "baz": 42} s = 0 for k, v in a.iteritems(): s = s + v # s == 46
Ruby
a = {"foo" => 1, "bar" => 3, "baz" => 42} s = 0 a.each do |k, v| s = s + v end # s == 46
Swift
let a = ["foo": 1, "bar": 3, "baz": 42] var s = 0 for (k, v) in a { s = s + v } // s == 46