News for hackers. Stuff that matters.
Re:The Swift Array Design (2014) by s3cur3 on Sunday March 21, 2021 @10:17PM (#26536159)
Swift's Array type is just so well designed. It's a delight to use.

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`.

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?
Re:The Swift Array Design (2014) by KMag on Monday March 22, 2021 @03:59AM (#26537952)
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.

Re:The Swift Array Design (2014) by jimbob45 on Sunday March 21, 2021 @11:30PM (#26536566)
Isn’t your second one just a simple ternary macro to check if null and return if so?
Re:The Swift Array Design (2014) by s3cur3 on Monday March 22, 2021 @06:51AM (#26539077)
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.

Re:The Swift Array Design (2014) by andijcr on Monday March 22, 2021 @04:32AM (#26538148)
for the first one, there is no direct equivalent, but you can directly loop over any [Derived] collection as a reference to [Base]
Re:The Swift Array Design (2014) by s3cur3 on Monday March 22, 2021 @06:46AM (#26539024)
True! It’s only an annoyance when you need to pass a std::vector<Derived> to a function that only accepts std::vector<Base>.