Help us understand the problem. What is going on with this article?

Objective-C の Dictionary は、キーに基本データ型が使えないのね

More than 5 years have passed since last update.

Obj-C 慣れないもので、こんな所でハマってた。
くやしいので他の言語と比較しておく。
当然ながら Dictionary に限った話でない(はず)。

Objective-C

Objective-C
NSMutableDictionary* dic = [[NSMutableDictionary alloc] init];
[dic setObject:@"hoge" forKey:[NSNumber numberWithInt:1]]; // これは OK
[dic setObject:@"huga" forKey:@1]; // これも OK (@1 は NSNumber のリテラル構文なので)
[dic setObject:@"piyo" forKey:2]; // これはダメ(落ちる

キーと値が他の言語と逆なのにまずハマって、
キーに int型 の値を入れてたのに気づかずまたハマった。
せめてコンパイルエラーにして欲しいよ。
言語仕様上、型指定できないのでキーも値もどんな型でも突っ込めちゃう、こわい。

Java

Java
Map<Integer, String> dic = new HashMap<Integer, String>();
Map<int, String> dic = new HashMap<int, String>(); // これはダメ(コンパイルできない)
dic.put(Integer.valueOf(1), "hoge"); // OK
dic.put(2, "piyo"); // これも OK(へー

int と Integer ってのがあって、int を使って HashMap を宣言できない。
これはコンパイル時に分かるので良いけど、int と Integer の変換が必要なことがしばしば。

C#

C#
var dic = new Dictionary<int, string>(); // 型推論&Generic
dic.Add(1, "hoge"); // OK
dic.Add(2, "piyo"); 
dic.Add(3, "huga"); 

一番スッキリ書けますね。
 
 
 

…Xamarin いいよ、Xamarin

amay077
ランチの時は呼ぶといい!
https://blog.amay0777.net/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした