[Pitch] Extending optional chains to include for loops

Actually I view that as an advantage. It would look exactly like a library feature (and the only thing making it different is that it can't be implemented as a pure library feature† that's why it is special-cased in the compiler), and users won't have to learn a new syntax. The "perceived" language size is not increased.

† or maybe it could?

// using MaybeSequence from https://forums.swift.org/t/pitch-extending-optional-chains-to-include-for-loops/65848/15

struct MaybeSequence<Wrapped: Sequence> {
    let wrapped: Wrapped?
}

extension MaybeSequence {
    struct Iterator {
        var wrapped: Wrapped.Iterator?
    }
}

extension MaybeSequence.Iterator: IteratorProtocol {
    mutating func next() -> Wrapped.Element? {
        wrapped?.next()
    }
}

extension MaybeSequence: Sequence {
    func makeIterator() -> Iterator {
        .init(wrapped: wrapped?.makeIterator())
    }
}

enum EmptySequence {
    case empty
}

func ?? <Wrapped> (lhs: Optional<Wrapped>, rhs: EmptySequence) -> MaybeSequence<Wrapped> {
    MaybeSequence(wrapped: lhs)
}

func test() {
    let y: [Int]? = [1, 2, 3]
    let z: [Int]? = nil
    
    for x in y ?? .empty {
        print(x)
    }
    for x in z ?? .empty {
        print(x)
    }
}

test()