Rust does this by modeling ownership as a part of the type system and thus something that generic types can abstract over. Swift doesn’t model ownership that way, so it can’t.
Sorry, but I still don't understand this statement. Here's my understanding:
This is a tradeoff that seems to swing in Swift's favor here — we can say what the lifetimes are for returned borrows, without any necessity that they apply in general to Escapable types.
Rust has:
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
Roughly in Swift:
public protocol Iterator: ~Copyable, ~Escapable {
associatedtype Item: ~Copyable, ~Escapable
@_lifetime(copy self) // justified below
mutating func next() -> Item?
}
Consuming Iteration
A consuming iterator given these definitions is simple:
struct MyIterator { ... }
impl Iterator for MyIterator {
type Item = Whatever;
fn next(&mut self) -> Option<Whatever> { ... }
}
struct MyIterator: ~Copyable, ~Escapable, Iterator {
mutating func next() -> Whatever? { ... }
}
Lifetimes don't apply in either language: in Rust you simply don't have any, in Swift they're irrelevant and ignored so long as Whatever is Escapable. This compiles in Swift 6.4.
Borrowing Iteration
In Rust, if you want to write a borrowing iterator, you have to write type Item = &'a T, where a is some generic lifetime parameter. The only place that lifetime parameter can live is on your iterator type, so a borrowing iterator kinda inherently looks like:
struct MyIterator<'a> { ... }
impl<'a> Iterator for MyIterator<'a> {
type Item = &'a Whatever;
fn next(&mut self) -> Option<&'a Whatever> { ... }
}
In Swift Ref takes on the lifetime declared on the method that returns it, so given the above translation of Iterator, you could write
struct MyIterator: ~Copyable, ~Escapable, Iterator {
typealias Item = Ref<Whatever>
@_lifetime(copy self) // most equivalent to the Rust code, but see below
mutating func next() -> Ref<Whatever> { ... }
}
The lifetime is now relevant, and has the same restriction as Rust — it must match whatever the Iterator was borrowed from. The same protocol supports borrowing iteration as well as consuming iteration. I can't test this in Swift 6.4 yet because Ref isn't in Xcode 27b1, but I believe it will compile.
Lending Iteration
That means you can't create a "lending" iterator, where the iterator itself has some internal storage that next returns a reference to. But in Swift (and unlike Rust, without getting into Generic Associated Types) we can further relax the protocol:
public protocol Iterator: ~Copyable, ~Escapable {
associatedtype Item: ~Copyable, ~Escapable
@_lifetime(borrow self)
mutating func next() -> Item?
}
Now the returned item can have a shorter lifetime than the iterator. The slight tradeoff is that now the reference to the item can't outlive the iterator, even when that would've been valid (it's borrowed from the container). So it's not a complete home-run, but a deliberate choice we can make in either direction.