Specifying types in functions

Hi all!
Posting this here since it is probably redundant, but I don't know how to word it to find it:

When a type is specified in a generic function like let foo = myPointer.load(as: UInt16.self) the .self in UInt16.self is required to make it a thing* the compiler can handle. However, from a developers perspective, it would be much more readable and intuitive to just write let foo = myPointer.load(as: UInt16) and have the compiler figure out the rest.

Is this a super bad idea, and compilers can't work like this? Or is this something that's being proposed or discussed? Where would I find this? What are the words/concepts I'm missing?

This is SE-0090, which was deferred for the reasons outlined in the rationale linked in the document. These remain largely applicable today and I don’t know that we have made any progress in that respect.

5 Likes

I think a reasonable approach would be to allow the omission of .self only in cases where it is unambiguous, while still requiring .self when it would be ambiguous.

Addressing the specific problems described in the decision rationale:

let x = [Int]

Not allowed. Write either [Int.self] for an array, or [Int].self for a type.

let x = ()

This is an empty tuple. Write let x = Void for the type.

• • •

Another option would be to say that the syntax sugar [T], [T: U], and T? cannot be used this way without .self, and instead to use Array<T>, Dictionary<T, U>, and Optional<T> if you want to omit .self.

1 Like

Right, I’m not claiming that there are no reasonable approaches, and various options have been outlined in this forum.

It’s just that this will necessitate a conversation among the whole community that hasn’t yet happened, and I think it’s worth considering whether, given the limited bandwidth we have here, tackling that now is prudent versus later (as it really can be done any time).

I guess in most cases where it's actually used, even the ambiguous cases aren't really ambiguous, since a Type is expected:

container.decode([Int], forKey: .someKey)

I think the best time this could have been done was when Codable was introduced, since explicitly stated types are used there a lot. But around that time, ABI stability became the #1 topic, so I understand it was postponed. Now that this is out of the way, I'd vote to get this back on the agenda :-)

3 Likes
Terms of Service

Privacy Policy

Cookie Policy