展开Swift可选,无需重新分配变量 [英] Unwrapping Swift optional without variable reassignment

查看:63
本文介绍了展开Swift可选,无需重新分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用可选绑定解开单个方法调用(或长方法调用链的可选链接)时,语法清晰易懂:

When using optional binding to unwrap a single method call (or optional chaining for a long method call chain), the syntax is clear and understandable:

if let childTitle = theItem.getChildItem()?.getTitle() {
    ...
}

但是,当将变量作为参数提供时,我发现自己使用了:

But, when provided the variable as a parameter, I find myself either using:

func someFunction(childTitle: String?) {
    if let theChildTitle = childTitle {
        ...
    }
}

,甚至只是用相同的名称重新定义它:

or even just redefining it with the same name:

if let childTitle = childTitle { ... }

我开始想知道是否有快捷方式或更有效地执行nil检查,其唯一目的是使用现有变量.我曾想过像这样的东西:

And I've started wondering if there is a shortcut or more efficient of performing a nil check for the sole purpose of using an existing variable. I've imagined something like:

if let childTitle { ... }

是否存在类似的东西,或者至少是上述两种临时解决方案的替代品?

Does something like this exist, or at least an alternative to my above two interim solutions?

推荐答案

否.您应该使用与您提到的名称相同的名称重新定义其选配项.这样,您无需创建第二个变量.

No. You should unwrap your optionals just redefining it with the same name as you mentioned. This way you don't need to create a second var.

func someFunction(childTitle: String?) {
    if let childTitle = childTitle {
        ...
    }
}

更新: Xcode 7.1.1•Swift 2.1

您还可以按如下方式使用防护功能:

You can also use guard as follow:

func someFunction(childTitle: String?) {
    guard let childTitle = childTitle else {
        return
    }

    // childTitle it is not nil after the guard statement
    print(childTitle)
}

这篇关于展开Swift可选,无需重新分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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