[Swift-devel] typed keys

Ben Clifford benc at hawaga.org.uk
Sun Jul 24 03:53:56 CDT 2011


OK.

First, there's a fourth alternative, that that [] means that the type inside that [] should be inferred (eg using something like hindley-millner] - from a user perspective that might look a bit like hategan's option 1: (have a universal type) but its keeps the array indices a single type: you can declare:

int a[]; a["f"]=10; a["q"]=20; or int a[]; a[4]=10; a[5]=20; but not int a[]; a["f"]=10; a[5]=20;

Type inference can introduce awkward-for-the-user error messages, though (which is what irked me when Milena prototyped it a few years ago for her summer-of-code project): The three statements:
 int a[]; a["f"]=10; a[5]=20;
are wrong, but in which of the three statements is there an error?

Maybe in this restricted case its ok, though?

I dislike the idea of introducing a type hierarchy without a lot more thinking of what it affects. For example, I think it can then introduce runtime type errors: 5+"monkey" (for example) or inability to add two numbers (5+5 = TYPE ERROR! because those 5s happen to be Objects not numbers)

If I had to choose between having a String and having a MagicScopeID type to represent the auto generated ID, I think I'd probabyl prefer the magicscopeid type. But I'm not massively convinced. Because although it produces a nice type separation, it doesn't stop you acquiring magicscopeid values. Although you can't construct them yourself, you can still extract them inside a foreach loop and do bad things: (a concern hategan raised):

 int a[magic]; int b[magic]; int c[magic];
populate(a); populate(b);
foreach v,k in a {
  foreach u,l in b {
    c[k] = "hello";
  }
}
will attempt to create duplicate entries in c, which is not permitted - so its not actually introducing much protection.
On the other hand, using a string ties it into the present implementation in a way that I think need not happen, and if you require explicit type declaration rather than [], then why does [string] make any more sense than [magicauto] ? (perhaps compare to how pointers are stored as ints; but you write foo *a; rather than  "int a; /* which will point to a foo */")

I think explicitly declaring the type of array indices is probably ok. You declare the type of pretty much everything else when you write the program, so why not this? The closest example in Java I can think of is maps that use Java generics:

    HashMap<Integer,String> map = new HashMap<Integer,String>();

where you declare both the key type and the value type.

Ben




More information about the Swift-devel mailing list