Hacker News new | ask | show | jobs
by alexjarvis 3837 days ago
Yeah you're right. If you want to stick with value types and store those values in an Array where the array can only store one type then you have to use an Enum instead of classes. I think there are a few people getting confused by not identifying enums in Swift as a more powerful construct than in C/ObjC.
1 comments

We basically have that same issue in Rust :)
And with associated values in enum types they behave in a similar way to case classes in Scala that extend a sealed trait.

For example I've been working on a Json library that stores everything in an enum (ADT):

  public enum JsValue {
    case JsString(String)
    case JsNumber(Double)
    case JsObject([String: JsValue])
    case JsArray([JsValue])
    case JsBoolean(Bool)
    case JsNull
  }
Don't trait objects (https://doc.rust-lang.org/stable/reference.html#trait-object...) solve this problem?
Well, yes. But that wasn't what I was talking about.

Trait objects in Rust let you emulate inheritance. The issue I was talking about is that folks from inheritance-heavy languages use this as the de facto design pattern, and then stuff doesn't work so well, because you're not supposed to use inheritance so much (the languages aren't designed with this in mind). The correct option is to use enums and composition over inheritance wherever possible.

In functional languages, functionality should be extrinsic (case match values from the outside), while in OO languages like functionality is intrinsic (polymorphic method members called on the value). However, for things like hashing, intrinsic works way better (hence traits, protocols, type classes, and so on).

Saying use composition over inheritance "wherever possible" can lead to some cargo culting on its own. It is always possible to use composition over inheritance, but it isn't always wise.

> but it isn't always wise.

Pretty much what I meant, when I said "wherever possible" I meant "wherever possible with decent code", sorry about the confusion.