UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Optional Chaining with Textfield

Forums > 100 Days of Swift

This line was used in Project 5 of 100DaysofSwift:

guard let answer = ac?.textFields?[0].text else { return }

Why is it that the optional chaining goes before the [0] and not after it?

Aren't we checking to make sure that the first textField which is [0] is there? And if it isn't returning nil and not proceeding with the chain.

When the ? is before the [0] it seems like we are checking whether there are any textFields at all and returning nil and cutting the chain short rather than checking specifically for the first chain.

Thanks for your time,

Mack

3      

@twostraws  Site AdminHWS+

Because the textFields array is optional – it might not exist.

5      

Thanks for such a quick response Paul!

3      

Just to add:

ac?.textFields?[0]

is in fact doing, as you might suspect, a test to see if the ac exists, and if it does then it tests to see if the textFields exist. The first item iin the array is then nil if one or both are nil.

if you could compile .textFields[0] then textFields would have to exist. However it doesnt return an optional if there is nothing at the first index, which is 0 in a zero based array.

Using the brackets works or causes an exception for out of bounds if the index is too large. There is no optional returned.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.