Indirect Members

Hello community,

With enums, you can have indirect cases:

enum Tree<T> {
   case Leaf(T)
   indirect case Node(Tree, Tree)
}

But with structs, last time I checked, you can not do

struct LinkedList<T> {
   var value : T
   indirect var tail : LinkedList<T>?
}

This may be tolerable for internal types, but what if you interface with a REST API from another company and some API call can return a type where the json schema is recursive? Do I just have to switch to reference types?

Maybe allowing to annotate optional struct members as indirect would be a cleaner solution in the future.

1 Like

How about this:

struct LinkedList<T> {
  var value: T
  var _tail: [LinkedList<T>]
  var tail: LinkedList<T>? {
    get { return _tail.first }
    set { _tail = [newValue] }
  }
}
3 Likes

The naive implementation of this would have to allocate for every new value, FWIW. Presumably you’re imagining Optional<Box<LinkedList>>, but it would actually be Box<Optional<LinkedList>> unless we made an exception for optionals.

3 Likes

Maybe Swift should define a (back-ported) Box type in the standard library so the ecosystem could use the same one.

public final class Box<T> { 
    public var wrappedValue: T { get set }
    public init(wrappedValue: T)
}

Then you can define your linked list as

struct LinkedList<T> {
   var value : T
   var tail : Box<LinkedList<T>>?
}

You may be interested in this pitch for the same feature:

2 Likes

ahhhh thanks, the preview didn't recommend this one as "similar" to me