Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to use for-in loop with an optional?

What's the proper way to use for-in loop with an optional?

Right now I always perform an optional binding before looping it. Are there other idioms?

let optionalInt:[Int]? = [1, 2, 3]  if let optionalInt = optionalInt {   for i in optionalInt {     print(i)   } } 
like image 952
Boon Avatar asked Sep 20 '15 19:09

Boon


People also ask

How do you run a for loop in Swift?

In Swift, the for-in loop is used to run a block of code for a certain number of times. It is used to iterate over any sequences such as an array, range, string, etc. Here, val accesses each item of sequence on each iteration. Loop continues until we reach the last item in the sequence .

How do you use optional binding?

An if statement is the most common way to unwrap optionals through optional binding. We can do this by using the let keyword immediately after the if keyword, and following that with the name of the constant to which we want to assign the wrapped value extracted from the optional.

How do I iterate in Swift?

You use the for - in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string. This example uses a for - in loop to iterate over the items in an array: let names = ["Anna", "Alex", "Brian", "Jack"]

Can let be optional in Swift?

It either contains data if you got information for that property, or nil. In that case it makes perfect sense to use an optional constant. You'd write an init method for your response object that would take the network reply (In JSON, for example) and fill out the properties of the response object.


1 Answers

If set of operations to be applied to all elements of the array, it is possible to replace for-loop with forEach{} closure and use optional chaining:

var arr: [Int]? = [1, 2, 3] arr?.forEach{print($0)} 
like image 106
Richard Topchii Avatar answered Sep 27 '22 20:09

Richard Topchii