Swift 安全地解包可选字符串和整数 [英] Swift safely unwrapping optinal strings and ints

查看:28
本文介绍了Swift 安全地解包可选字符串和整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我要为第二个视图启动 segue 时,我还会发送一些如下值:

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
}

在第二个 VC 中,我声明了如下变量:

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!
}

这一切都有效,我从来没有因为未包装的变量或 nil 值而出现任何错误.但是有没有更简单的方法呢?

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

现在感觉我检查太多了

推荐答案

我能想到三个替代方案.

I can think of three alternatives.

  1. if/let.与您当前的选项非常相似,但您不必隐式解包.

  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
}

您甚至可以在同一行打开它们.这样做的缺点是,如果其中一个是 nil,那么两个标签都不会被设置.

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
}

  • 保护/让.如果这些位于 setupViews() 之类的函数中,那么您可以像这样单行展开:

  • 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
    }
    

  • 您可以使用默认值和 ?? 运算符来快速解包.

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

  • 这篇关于Swift 安全地解包可选字符串和整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆