如何在Swift中压缩解包多个选项? [英] How do I condense unwrapping multiple optionals in Swift?

查看:154
本文介绍了如何在Swift中压缩解包多个选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解开这6个可选变量,如果它们为null,我想给它们一个空白的String值。这样我就可以将这些变量打包到一个发送到API的参数数组中。

I want to unwrap these 6 optional variables, and if they are null i want to give them a blank String value. This is so I can send these variables packaged into a parameters array that's sent to an API.

我仍然是Swift的初学者,这是我理解如何实现这一点的唯一最简单的方法,但我内心的编码器说这看起来多余和****一样蹩脚。

I'm still a beginner at Swift, and this is the only easiest way I have understood how to implement this, but the inner coder in me is saying this looks redundant and crappy as ****.

有人可以帮我缩小或简化吗?

Can someone help me condense this or make it simpler?

    if let fbEmail = self.fbEmail {

    }else{
        self.fbEmail = ""
    }

    if let fbDob = self.fbDob {

    }else{
        self.fbDob = ""
    }

    if let fbGender = self.fbGender {

    }else{
        self.fbGender = ""
    }
    if let fbUserIp = self.fbUserIp {

    }else{
        self.fbUserIp = ""
    }
    if let fbFacebookId = self.fbFacebookId {

    }else{
        self.fbFacebookId = ""
    }
    if let fbFacebookAccessToken = self.fbFacebookAccessToken {

    }else{
        self.fbFacebookAccessToken = ""
    }


推荐答案

你可以用6行代码完成:

You can do that in exactly 6 lines of code:

self.fbEmail  = self.fbEmail  ?? ""
self.fbDob    = self.fbDob    ?? ""
self.fbGender = self.fbGender ?? ""
self.fbUserIp = self.fbUserIp ?? ""
self.fbFacebookId = self.fbFacebookId ?? ""
self.fbFacebookAccessToken = self.fbFacebookAccessToken ?? ""

修改 的内容?? 语法:这是一个快捷方式如果nil指定另一个值:

what's up with the ?? syntax: It's a shortcut "if nil assign another value":

let c = a ?? b

将分配 c = a 如果 a!= nil ,否则 c = b

这篇关于如何在Swift中压缩解包多个选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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