2

I am trying to convert some code from Swift 1.2 to 2.0. I have the below code in Swift 1.2

//enable OR disable keys.
if(discountAmountTextField.text.isEmpty){
    keypadView.disableNotRequiredKeys()
}else{
    keypadView.enableRequiredKeys()
}

There are two ways I can go about converting this to Swift 2.0 guard and if let

Here's how the code looks like with if let

//enable OR disable keys.
if let text = discountAmountTextField.text {
    if text.isEmpty {
        keypadView.disableNotRequiredKeys()
    } else {
        keypadView.enableRequiredKeys()
    }
} else {
    keypadView.enableRequiredKeys()
}

Here's how it looks using the guard syntax

//enable OR disable keys.
guard let text = discountAmountTextField.text else {
    keypadView.enableRequiredKeys()
    return;
}
if text.isEmpty {
    keypadView.disableNotRequiredKeys()
} else {
    keypadView.enableRequiredKeys()
}

I want to know what is considered as a more cleaner and appropriate way of writing. The guard looks cleaner to me but is there a rule of when I should be using one over the other? Is there any way to further simplify the method?

David Snabel
  • 9,801
  • 6
  • 21
  • 29
tbag
  • 1,268
  • 2
  • 16
  • 34
  • 2
    Use "if let ... where ...". – gnasher729 Oct 01 '15 at 16:13
  • 1
    There is a good answer here: http://stackoverflow.com/questions/30791488/swift-2-guard-keyword – Kitson Oct 01 '15 at 16:14
  • 2
    "guard" is there to watch for conditions that shouldn't usually happen and handle them. So it looks quite inappropriate here. – gnasher729 Oct 01 '15 at 16:14
  • 1
    @gnasher729 is right. Something like `if let text = discountAmountTextField.text where text.isEmpty { ... } else { ... }` – Mike Pollard Oct 01 '15 at 16:17
  • Changed it to `//enable OR disable keys. if let text = discountAmountTextField.text where text.isEmpty { keypadView.disableNotRequiredKeys() } else { keypadView.enableRequiredKeys() }` Thanks! – tbag Oct 01 '15 at 16:31

2 Answers2

4

I'd use a where here:

if let text = discountAmountTextField.text where text.isEmpty {
    keypadView.disableNotRequiredKeys()
} else {
    keypadView.enableRequiredKeys()
}

It combines two of your failure cases into one.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
1

You can avoid both, I guess.

You could rewrite your code like this:

switch discountAmountTextField.text?.isEmpty {
  case .Some(let value) where value:
      keypadView.disableNotRequiredKeys()
  case .Some(let value) where !value:
      keypadView.enableRequiredKeys()
  case _ :
      keypadView.enableRequiredKeys()
}

Compact, and still readable.

guard statements, in my opinion, are not the best when it comes to readability.

Also, as @gnasher729 suggests, this is not the best case to use it.

if let are slightly more readable, but you'll have to indent your code.

Notes

In my assumption:

discountAmountTextField is an instance of UITextField

Matteo Pacini
  • 21,796
  • 7
  • 67
  • 74