Re:The Swift Array Design (2014)
by higerordermap on Monday March 22, 2021 @01:34AM
(#26537154)
As someone who hasn't used swift, are there same array covariance problems as C#/Java due to implicit casting?
I was wondering the same thing. The linked article explains that they use an extra layer of indirection to perform copy-on-write for implicit upcasts. So, you can upcast in O(1), but your first write to the upcast array has an O(N) cost.
The upcast is type sound, unlike Java, but at the cost of an extra indirection, and a big hit for the first mutation after upcast. I would have been tempted to instead just have immutable array references that could be freely upcast, but this is also an elegant and safe solution.
Isn’t your second one just a simple ternary macro to check if null and return if so?
Not in C++ or Swift, no—to do it in the general case requires trying to cast each member of the array to the Derived type, and returning the null optional if any of those conversions fails.
E.g., given an array of Animal, you’d like to see if you can convert it to an array of Dog. Neither the compiler nor the runtime stores information on the array itself to say “it just so happens that the concrete Animal type of all the things I hold is [Dog/Cat/a mix of both],” so you have to go through the elements one by one.
for the first one, there is no direct equivalent, but you can directly loop over any [Derived] collection as a reference to [Base]
Two things stood out to me here as being really nice for someone coming from C++:
- Implicit upcasting to convert `[Derived]` to `[Base]` in O(1).
- Checked conversions convert `[T]` to `[U]?` in O(N) via `a as [U]` in O(n).
These are both operations I've manually written the C++ code to do, because there's no ergonomic way to do it with `std::vector`.