Search code examples
swiftoption-typeguard

Would using Swift's Guard or if Let Keywords take care of not having to use this checkNil function?


I understand that programming in a language such as Swift, intent can be expressed in numerous ways. I'm following a tutorial and saw the code below which isn't what I'm used to seeing because the author created a function to check for nil. Could the checkNil function be avoided by simply using guard or if let statements or does improve the code somehow? It's a great tutorial and I'm simply looking to improve my knowledge of interpreting other developer's code to find ways to be more concise myself.

import UIKit

class ViewController: UIViewController {

    private let rideService = DummyRideService()

    private var rides = [Ride]()

    @IBOutlet var from: UITextField!

    @IBOutlet var to: UITextField!

    @IBOutlet var ridesTableView: UITableView!

    @IBAction func findRouteButtonClicked(){
        let fromText = self.checkNil(from.text as AnyObject?)
        let toText = self.checkNil(to.text as AnyObject?)

    }

    func checkNil(_ string: AnyObject?) -> String {
        return string == nil ? "": string as! String
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Solution

  • there are many ways to get rid of the entire checkNil(_:) nonsense quickly.


    idea #1

    I'd just simply make the outlets optional weak properties then use optional chaining, like:

    @IBOutlet private weak var from: UITextField?
    @IBOutlet private weak var to: UITextField?
    

    then you could use this:

    @IBAction func findRouteButtonClicked() {
    
        let fromText = from?.text ?? ""
        let toText = to?.text ?? ""
    }
    

    idea #2

    or if you want to make it more elegant, you could create an extension on UITextField, like:

    extension UITextField {
    
        var alwaysText: String {
            return self.text ?? ""
        }
    }
    

    so you could replace the let lines with these more readable ones, like

    @IBAction func findRouteButtonClicked() {
    
        let fromText = from.alwaysText
        let toText = to.alwaysText
    }