检查字符串是否为零&空的 [英] Check string for nil & empty

查看:87
本文介绍了检查字符串是否为零&空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Swift中检查nil""的字符串?在Rails中,我可以使用blank()进行检查.

Is there a way to check strings for nil and "" in Swift? In Rails, I can use blank() to check.

我目前有这个,但似乎矫kill过正:

I currently have this, but it seems overkill:

    if stringA? != nil {
        if !stringA!.isEmpty {
            ...blah blah
        }
    }

推荐答案

如果您要处理可选的字符串,则可以:

If you're dealing with optional Strings, this works:

(string ?? "").isEmpty

?? nil合并运算符如果非nil,则返回左侧,否则返回右侧.

The ?? nil coalescing operator returns the left side if it's non-nil, otherwise it returns the right side.

您还可以像这样使用它来返回默认值:

You can also use it like this to return a default value:

(string ?? "").isEmpty ? "Default" : string!

这篇关于检查字符串是否为零&空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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