SwiftyJD SwiftyJD - 1 year ago 37
iOS Question

How to make switch statement with optionals?

I'm working with text fields and json data. I want to test if the json data is != nil, if it is, then I fill it's field with that info, if it's == nil then I put a placeholder in its field instead. Like this:

if memberInfo?.createDate != nil {

self.activeSinceTextField.text = stringToDateToString((memberInfo?.createDate)!)

} else {
placeHolder("Enter Here".localized())
self.activeSinceTextField.attributedPlaceholder = placeHolderText

if memberInfo?.birthDate != nil

{self.birthdayTextField.text = stringToDateToString((memberInfo?.birthDate)!)

} else

{ placeHolder("Enter Here".localized())
self.birthdayTextField.attributedPlaceholder = placeHolderText

I have a lot of fields and I'm thinking a switch statement would make this a lot cleaner. I'm just not sure how to make one for this type of situation.

Answer Source

Version 1

This is how you define the 4 outcomes with a switch

switch (memberInfo?.createDate, memberInfo?.birthDate) {
case (.Some, .Some): break
case (.Some, nil): break
case (nil, .Some): break
case (nil, nil): break

Now just replace the break(s) with the code you want to execute for each scenario.

Version 2

Here you have createDate and/or birthDate unwrapped when available

switch (memberInfo?.createDate, memberInfo?.birthDate) {
case (let .Some(createDate), let .Some(birthDate)):
    print(createDate, birthDate)
case (let .Some(createDate), .None):
case (.None, let .Some(birthDate)):
case (.None, .None):
    print("Both are nils")

Version 3

In this version I am using the fallthrough instruction to continue the evaluation of the second case even when the first case is satisfied.

So now the first and the second case are NOT mutual exclusive, they can BOTH be executed.

Infact the first case is executed when createDate is populated, regardless from birthDate. The second case is executed when birthDate is populated, regardless from createDate.

switch (memberInfo?.createDate, memberInfo?.birthDate) {
case (.Some, _):
    print("createDate is populated")
case (_, .Some):
    print("birthDate is populated")
default: break


  • .Some: means here there is something
  • .None: means this is nil
  • _: means is a jolly, it means I don't care what there is here