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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.