Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift for in loop with parentheses

I normally use the for in loop in swift without parentheses, but today I put them on just for kicks thinking they were just optional and it did not worked as expected.

This code works:

if let tasks = getAllTasksWithManagedObjectContext(appDelegate.managedObjectContext){
    for task in tasks{
        appDelegate.managedObjectContext.deleteObject(task)
    }
}

This one does not:

if let tasks = getAllTasksWithManagedObjectContext(appDelegate.managedObjectContext){
    for (task in tasks){
        appDelegate.managedObjectContext.deleteObject(task)
    }
}

I get this errors: enter image description here Whats going on here?

like image 281
the Reverend Avatar asked Dec 20 '25 07:12

the Reverend


1 Answers

You are simply not allowed to use parentheses here.

Take a look at the Language Reference -> Statements and compare the C-style for-loop against the swift for-in

for-statement → for­ for-init­;­expression­expression­ ­code-block
for-statement → for­ (for-init­;­expression­expression­) ­code-block

vs.

for-in-statement → for ­case(opt) ­pattern ­in ­expression ­where-clause­(opt­) code-block

The first one can be used with or without parentheses - your choice as the developer.

However the later one, the one you are actually asking about does not have a version with ( and ), only the one version without them. That means that it is not allowed to use them parentheses around the "argument" of the loop.

Screenshots from the docs linked above for better readability:

enter image description here
vs.
enter image description here

like image 145
luk2302 Avatar answered Dec 21 '25 22:12

luk2302



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!