David Sanford David Sanford - 2 months ago 6
Swift Question

Making text and Integer input fields optional Swift

Probably simple, but answer escapes me.

I have an IB with many input fields. Some are text and some are integers.

I need to set these up so they are optional, as I want the user not be required to completed all fields.

This data will be saved in core data.

Here is the current chain of events:

@IBOutlet weak var diveSiteTextfield: UITextField!
@IBOutlet weak var diveDurationTextfield: UITextField!

-------
let dd = Int(diveDurationTextfield.text!)
let dd1 = Int32(dd!)

diveLogbook.diveSite = diveSiteTextfield.text
diveLogbook.diveDuration = dd1


The above are just an example on one text and one integer.

Answer

You can use ?: and ?? to provide default values for them:

diveLogbook.diveSite = diveSiteTextfield.text?.isEmpty ? "Default Dive Site" : diveSiteTextfield.text
diveLogbook.diveDuration = Int32(diveDurationTextfield.text!) ?? 5

Change the default values as needed.