Avatar
@swift-5.2.5 import Foundation protocol P { var prev: P? { get set } } struct Foo: P, CustomStringConvertible { var prev: P? let uuid = UUID() var description: String { "Foo(prev: \(prev.map { String(describing: $0) } ?? "nil"), uuid: \(uuid.uuidString.prefix(4)))" } } func insert(_ p: P, into array: inout [P], _ prev: inout P?) { var p = p p.prev = prev prev = p print("new p =", p) array.append(p) } var p: P? var result: [P] = [] insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) for r in result { print("inserted =", r) } print("last 'p' =", p!)