[swift-users] for with optional collection?

Rick Mann rmann at latencyzero.com
Fri Feb 10 16:02:05 CST 2017


How would you write 

for x in array as? <something>

With parentheses? I like "in?" because it mimics "as?".

Sent from my iPhone

> On Feb 10, 2017, at 13:57, Jacob Bandes-Storch <jtbandes at gmail.com> wrote:
> 
> To me it would seem more logical as "for x in array? { }" — to parallel "for case let x? in array { }"
> 
> 
>> On Fri, Feb 10, 2017 at 1:03 PM, Rick Mann via swift-users <swift-users at swift.org> wrote:
>> I love the idea of for in? (Or even for? In). You should pitch that to evolution. 
>> 
>> Sent from my iPhone
>> 
>>> On Feb 10, 2017, at 07:04, Tino Heth <2th at gmx.de> wrote:
>>> 
>>> 
>>>> Is there any concise way to write the following?
>>>> 
>>>> if let collection = someOptionalCollection
>>>> {
>>>>    for item in collection
>>>>    {
>>>>    }
>>>> }
>>> I've been thinking about that lately, but haven't had the time to look wether someone on evolution already proposed a "for in?"-loop…
>>> 
>>> 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.
>>> 
>>> for i in? test {
>>> 	print(i)
>>> }
>>> 
>>> Imho looks even better, but this would need an extension of the language itself…
>>> 
>> 
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
>> 
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170210/00835548/attachment.html>


More information about the swift-users mailing list