Why doesn’t `CollectionOfOne<Element>` have an `element` property?

CollectionOfOne will always contain (exactly) one element. and yet, first and last are both optional, and don’t provide a way to extract the single element without a force-unwrap.

Subscript [0] fits the bill, methinks?

1 Like

that’s pretty much just collection.first!, is it not?

…without a force unwrap (the underlying _element is yielded directly), which is the desideratum?

1 Like

I think the point is most places the type is used is in generic contexts, as it’s basically intended as an efficient bridge to apply generic sequence algorithms when you statically only have a single element. It’s an abstract wrapper so it doesn’t really make much sense to add convenience API to the type itself.

However, it’s documented that the start index is always ‘0’ so you can subscript collectionOfOne[0] to get the element out without unwrapping.

i disagree with this. i am using CollectionOfOne<T> in encoding/decoding contexts, where CollectionOfOne<T> maps to a single-element array/list/tuple/vector in the coding schema.

You can just add it yourself:

extension CollectionOfOne {
  public var element: Element { self[startIndex] }
}