user2636197 user2636197 - 5 months ago 11
Swift Question

Swift safely unwrapping optinal strings and ints

When I am about to fire my segue for the 2nd view I also send some values like this:

if let aTime = ads[indexPath.row]["unix_t"].int {
toView.time = aTime
}

if let aTitle = ads[indexPath.row]["title"].string {
toView.title = aTitle
}


In the second VC I have declared the varibles like:

var time: Int?
var title: String?


and this is how I unwrap the values:

if time != nil {
timeLabel.text = String(time!)
}

if title != nil {
titleLabel.text = title!
}


This all works I never get any error caused by unwrapped varibles or nil values. But is there any easier way to do it?

Right now it feels like I am checking too much

Answer

I can think of three alternatives.

  1. if/let. Very similar to your current option, but you don't have to implicitly unwrap.

    if let time = time {
        timeLabel.text = "\(time)"
    }
    
    if let title = title {
        titleLabel.text = title
    }
    

    You can even unwrap them on the same line. The downside to this is that if one of them is nil, then neither label will be set.

    if let time = time, let title = title {
        timeLabel.text = "\(time)"
        titleLabel.text = title
    }
    
  2. guard/let. If these are in a function like setupViews(), then you can one-line your unwrapping like so:

    func setupViews() {
        guard let time = time, let title = title else { return }
        timeLabel.text = "\(time)"
        titleLabel.text = title
    }
    
  3. You can use default values and the ?? operator to unwrap quickly.

    timeLabel.text = "\(time ?? 0)"
    titleLabel.text = title ?? ""