3 ms·
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++: - Implic
by s3cur3 6y ago
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`.
- jimbob45 6y agoIsn’t your second one just a simple ternary macro to check if null and return if so?
- s3cur3 6y agoNot 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.
- higerordermap 6y agoAs someone who hasn't used swift, are there same array covariance problems as C#/Java due to implicit casting?
- KMag 6y agoI 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.
- deleted 6y ago[deleted]
- andijcr 6y agofor the first one, there is no direct equivalent, but you can directly loop over any [Derived] collection as a reference to [Base]
- s3cur3 6y agoTrue! It’s only an annoyance when you need to pass a std::vector<Derived> to a function that only accepts std::vector<Base>.