Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift optional binding in while loop

Tags:

swift

According to Swift documentation:

Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.

The documentation only shows an example of optional-binding using if statement like:

if let constantName = someOptional {
    statements
}

I'm looking for an example of optional-binding using while loop?

like image 601
Abdelsalam Shahlol Avatar asked Jan 18 '18 10:01

Abdelsalam Shahlol


People also ask

What is Optional binding in Swift example?

Optional Binding is used to safely unwrap the optional value. Step Two: If the optional variable contains a value it will be assigned to our temporary variable. Step Three: When the program executes it will execute the first branch and unwrap our optional safely.

What is Optional binding and Optional chaining in Swift?

Optional binding stores the value that you're binding in a variable. 2. Optional chaining doesn't allows an entire block of logic to happen the same way every time. 2. Optional binding allows an entire block of logic to happen the same way every time.

What is Optional chaining in Swift?

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil . If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil , the property, method, or subscript call returns nil .


1 Answers

It's the same

while let someValue = someOptional
{
    doSomethingThatmightAffectSomeOptional(with: someValue)
}

Here is a concrete example of iterating a linked list.

class ListNode
{
    var value: String
    var next: ListNode?

    init(_ value: String, _ tail: ListNode?)
    {
        self.value = value
        self.next = tail
    }
}

let list = ListNode("foo", ListNode("bar", nil))

var currentNode: ListNode? = list
while let thisNode = currentNode
{
    print(thisNode.value)
    currentNode = thisNode.next
}

// prints foo and then bar and then stops
like image 199
JeremyP Avatar answered Oct 05 '22 17:10

JeremyP