[swift-evolution] for in? optionalCollection {

Tino Heth 2th at gmx.de
Sun Feb 12 07:45:21 CST 2017

Most alternatives already where discussed in swift-user:

> Imho the "forEach" solution is flawed, because you can't break the loop, and the "?? []" isn't perfect either:
> I hope the compiler can optimise so that the assembly is as fast as the "if let" solution, but even if this is the case, it is not obvious for a human reader.
> This
> extension Optional where Wrapped: Sequence {
> 	var elements: [Wrapped.Iterator.Element] {
> 		switch (self) {
> 		case .none:
> 		return []
> 		case .some(let o):
> 		return Array(o)
> 		}
> 	}
> }
> let test: [Int]? = nil
> for i in test.elements {
> 	print(i)
> }
> looks nice to me (except the return type — I guess there are better options), but I don't expect that the compiler can do much to optimise it.

But maybe there is something better:

for i in test? {
	if i == 42 {

This doesn't work — but it compiles fine when you replace the "?" with "!".

I haven't proposed "in?" earlier because it would be a new keyword (even if its not that new…), and I'm very skeptical towards such changes.
But it is a very common pattern in Swift to have a "!" form that may crash and a save "?" variant, so I think it is actually missing in the syntax of for-loops.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170212/2dc240f6/attachment.html>

More information about the swift-evolution mailing list