For-In Loops Multiple Terms

With the new upgrade to Xcode 7.3, there were many problems with the new version of Swift 3. One of them says: "The C-style statement for older versions is outdated and will be removed in a future version of Swift" (this appears in traditional for expressions).

One of these cycles has more than one condition:

 for i = 0; i < 5 && i < products.count; i += 1 { } 

My question is, is there a graceful way (do not use a break ), to include this double condition of the built-cycle Swift:

 for i in 0 ..< 5 { } 
+5
source share
4 answers

It would be the same as you say if you described it out loud:

 for i in 0 ..< min(5, products.count) { ... } 

However, I suspect that you really mean:

 for product in products.prefix(5) { ... } 

which is less error prone than anything that requires a subscription.

Perhaps you really need an integer index (although this is rare), in which case you mean:

 for (index, product) in products.enumerate().prefix(5) { ... } 

Or you can even get a real index if you want:

 for (index, product) in zip(products.indices, products).prefix(5) { ... } 
+12
source

You can use the && operator with the where clause, for example

 let arr = [1,2,3,4,5,6,7,8,9] for i in 1...arr.count where i < 5 { print(i) } //output:- 1 2 3 4 for i in 1...100 where i > 40 && i < 50 && (i % 2 == 0) { print(i) } //output:- 42 44 46 48 
+9
source

Another way to do this would be as follows:

 for i in 0 ..< 5 where i < products.count { } 
+4
source

Here is a simple solution:

 var x = 0 while (x < foo.length && x < bar.length) { // Loop body goes here x += 1 } 
-1
source

Source: https://habr.com/ru/post/1245714/


All Articles