简体   繁体   English

检查字符串是否为 nil 和空

[英]Check string for nil & empty

Is there a way to check strings for nil and "" in Swift?有没有办法检查 Swift 中的nil""字符串? In Rails, I can use blank() to check.在 Rails 中,我可以使用blank()来检查。

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

The ?? ?? nil coalescing operator returns the left side if it's non-nil, otherwise it returns the right side. nil 合并运算符如果非 nil 返回左侧,否则返回右侧。

You can also use it like this to return a default value:您也可以像这样使用它来返回默认值:

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

You could perhaps use the if-let-where clause:您也许可以使用 if-let-where 子句:

Swift 3:斯威夫特 3:

if let string = string, !string.isEmpty {
    /* string is not blank */
}

Swift 2:斯威夫特 2:

if let string = string where !string.isEmpty {
    /* string is not blank */
}

Using the guard statement使用guard语句

I was using Swift for a while before I learned about the guard statement.在我了解guard语句之前,我使用了 Swift 一段时间。 Now I am a big fan.现在我是一个大粉丝。 It is used similarly to the if statement, but it allows for early return and just makes for much cleaner code in general.它的用法与if语句类似,但它允许提前返回,并且通常会使代码更简洁。

To use guard when checking to make sure that a string is neither nil nor empty, you can do the following:要在检查时使用保护以确保字符串既不为零也不为空,您可以执行以下操作:

let myOptionalString: String? = nil

guard let myString = myOptionalString, !myString.isEmpty else {
    print("String is nil or empty.")
    return // or break, continue, throw
}

/// myString is neither nil nor empty (if this point is reached)
print(myString)

This unwraps the optional string and checks that it isn't empty all at once.这会解开可选字符串并检查它是否一次全部为空。 If it is nil (or empty), then you return from your function (or loop) immediately and everything after it is ignored.如果它为零(或空),则立即从函数(或循环)返回,并忽略它之后的所有内容。 But if the guard statement passes, then you can safely use your unwrapped string.但是如果保护语句通过,那么您可以安全地使用解包的字符串。

See Also也可以看看

If you are using Swift 2, here is an example my colleague came up with, which adds isNilOrEmpty property on optional Strings:如果您使用的是 Swift 2,这里是我同事提出的一个示例,它在可选字符串上添加了 isNilOrEmpty 属性:

protocol OptionalString {}
extension String: OptionalString {}

extension Optional where Wrapped: OptionalString {
    var isNilOrEmpty: Bool {
        return ((self as? String) ?? "").isEmpty
    }
}

You can then use isNilOrEmpty on the optional string itself然后您可以在可选字符串本身上使用 isNilOrEmpty

func testNilOrEmpty() {
    let nilString:String? = nil
    XCTAssertTrue(nilString.isNilOrEmpty)

    let emptyString:String? = ""
    XCTAssertTrue(emptyString.isNilOrEmpty)

    let someText:String? = "lorem"
    XCTAssertFalse(someText.isNilOrEmpty)
}

With Swift 5, you can implement an Optional extension for String type with a boolean property that returns if an optional string is empty or has no value:使用 Swift 5,您可以使用布尔属性实现String类型的Optional扩展,该属性在可选字符串为空或没有值时返回:

extension Optional where Wrapped == String {

    var isEmptyOrNil: Bool {
        return self?.isEmpty ?? true
    }

}

However, String implements isEmpty property by conforming to protocol Collection .但是, String通过符合协议Collection来实现isEmpty属性。 Therefore we can replace the previous code's generic constraint ( Wrapped == String ) with a broader one ( Wrapped: Collection ) so that Array , Dictionary and Set also benefit our new isEmptyOrNil property:因此,我们可以用更广泛的约束( Wrapped == String Wrapped: Collection )替换之前代码的通用约束( Wrapped == String ),以便ArrayDictionarySet也有利于我们的新isEmptyOrNil属性:

extension Optional where Wrapped: Collection {

    var isEmptyOrNil: Bool {
        return self?.isEmpty ?? true
    }

}

Usage with String s:String使用:

let optionalString: String? = nil
print(optionalString.isEmptyOrNil) // prints: true
let optionalString: String? = ""
print(optionalString.isEmptyOrNil) // prints: true
let optionalString: String? = "Hello"
print(optionalString.isEmptyOrNil) // prints: false

Usage with Array s:Array使用:

let optionalArray: Array<Int>? = nil
print(optionalArray.isEmptyOrNil) // prints: true
let optionalArray: Array<Int>? = []
print(optionalArray.isEmptyOrNil) // prints: true
let optionalArray: Array<Int>? = [10, 22, 3]
print(optionalArray.isEmptyOrNil) // prints: false

Sources:资料来源:

var str: String? = nil

if str?.isEmpty ?? true {
    print("str is nil or empty")
}

str = ""

if str?.isEmpty ?? true {
    print("str is nil or empty")
}

I know there are a lot of answers to this question, but none of them seems to be as convenient as this (in my opinion) to validate UITextField data, which is one of the most common cases for using it:我知道这个问题有很多答案,但似乎没有一个像这样方便(在我看来)验证UITextField数据,这是使用它的最常见情况之一:

extension Optional where Wrapped == String {
    var isNilOrEmpty: Bool {
        return self?.trimmingCharacters(in: .whitespaces).isEmpty ?? true
    }
}

You can just use你可以使用

textField.text.isNilOrEmpty

You can also skip the .trimmingCharacters(in:.whitespaces) if you don't consider whitespaces as an empty string or use it for more complex input tests like如果您不将空格视为空字符串或将其用于更复杂的输入测试,您也可以跳过.trimmingCharacters(in:.whitespaces)

var isValidInput: Bool {
    return !isNilOrEmpty && self!.trimmingCharacters(in: .whitespaces).characters.count >= MIN_CHARS
}

I would recommend.我会推荐。

if stringA.map(isEmpty) == false {
    println("blah blah")
}

map applies the function argument if the optional is .Some .如果可选是.Somemap应用函数参数。
The playground capture also shows another possibility with the new Swift 1.2 if let optional binding.如果让可选绑定,操场捕获还显示了新 Swift 1.2 的另一种可能性。

在此处输入图片说明

If you want to access the string as a non-optional, you should use Ryan's Answer , but if you only care about the non-emptiness of the string, my preferred shorthand for this is如果您想将字符串作为非可选访问,您应该使用Ryan's Answer ,但如果您只关心字符串的非空性,我的首选简写是

if stringA?.isEmpty == false {
    ...blah blah
}

Since == works fine with optional booleans, I think this leaves the code readable without obscuring the original intention.由于==与可选的布尔值一起工作得很好,我认为这使得代码可读,而不会掩盖最初的意图。

If you want to check the opposite: if the string is nil or "" , I prefer to check both cases explicitly to show the correct intention:如果你想检查相反的:如果字符串是nil"" ,我更喜欢明确检查这两种情况以显示正确的意图:

if stringA == nil || stringA?.isEmpty == true {
    ...blah blah
}

SWIFT 3斯威夫特 3

extension Optional where Wrapped == String {

    /// Checks to see whether the optional string is nil or empty ("")
    public var isNilOrEmpty: Bool {
        if let text = self, !text.isEmpty { return false }
        return true
    }
}

Use like this on optional string:像这样在可选字符串上使用:

if myString.isNilOrEmpty { print("Crap, how'd this happen?") } 

Swift 3 For check Empty String best way Swift 3 用于检查空字符串的最佳方式

if !string.isEmpty{

// do stuff

}

You can create your own custom function, if that is something you expect to do a lot.您可以创建自己的自定义函数,如果这是您希望做的很多事情的话。

func isBlank (optionalString :String?) -> Bool {
    if let string = optionalString {
        return string.isEmpty
    } else {
        return true
    }
}



var optionalString :String? = nil

if isBlank(optionalString) {
    println("here")
}
else {
    println("there")
}

Swift 3 solution Use the optional unwrapped value and check against the boolean. Swift 3 解决方案使用可选的解包值并检查布尔值。

if (string?.isempty == true) {
    // Perform action
}

Using isEmpty使用 isEmpty

"Hello".isEmpty  // false
"".isEmpty       // true

Using allSatisfy使用 allSatisfy

extension String {
  var isBlank: Bool {
    return allSatisfy({ $0.isWhitespace })
  }
}

"Hello".isBlank        // false
"".isBlank             // true

Using optional String使用可选字符串

extension Optional where Wrapped == String {
  var isBlank: Bool {
    return self?.isBlank ?? true
  }
}

var title: String? = nil
title.isBlank            // true
title = ""               
title.isBlank            // true

Reference : https://useyourloaf.com/blog/empty-strings-in-swift/参考: https : //useyourloaf.com/blog/empty-strings-in-swift/

This is a general solution for all types that conform to the Collection protocol, which includes String :这是所有符合Collection协议的类型的通用解决方案,其中包括String

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        self?.isEmpty ?? true
    }
}

Create a String class extension:创建一个 String 类扩展:

extension String
{   //  returns false if passed string is nil or empty
    static func isNilOrEmpty(_ string:String?) -> Bool
    {   if  string == nil                   { return true }
        return string!.isEmpty
    }
}// extension: String

Notice this will return TRUE if the string contains one or more blanks.请注意,如果字符串包含一个或多个空格,这将返回 TRUE。 To treat blank string as "empty", use...要将空白字符串视为“空”,请使用...

return string!.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty

... instead. ... 反而。 This requires Foundation.这需要基金会。

Use it thus...这样使用它...

if String.isNilOrEmpty("hello world") == true 
{   print("it's a string!")
}

Swift 3 This works well to check if the string is really empty. Swift 3 这可以很好地检查字符串是否真的为空。 Because isEmpty returns true when there's a whitespace.因为 isEmpty 在有空格时返回 true。

extension String {
    func isEmptyAndContainsNoWhitespace() -> Bool {
        guard self.isEmpty, self.trimmingCharacters(in: .whitespaces).isEmpty
            else {
               return false
        }
        return true
    }
}

Examples:例子:

let myString = "My String"
myString.isEmptyAndContainsNoWhitespace() // returns false

let myString = ""
myString.isEmptyAndContainsNoWhitespace() // returns true

let myString = " "
myString.isEmptyAndContainsNoWhitespace() // returns false

You should do something like this:你应该做这样的事情:
if !(string?.isEmpty ?? true) { //Not nil nor empty }

Nil coalescing operator checks if the optional is not nil, in case it is not nil it then checks its property, in this case isEmpty. Nil 合并运算符检查可选项是否不是 nil,如果它不是 nil,则检查它的属性,在这种情况下是 isEmpty。 Because this optional can be nil you provide a default value which will be used when your optional is nil.因为这个可选可以为零,所以你提供了一个默认值,当你的可选为 nil 时将使用该默认值。

Based on this Medium post , with a little tweak for Swift 5, I got to this code that worked.基于这篇 Medium 帖子,对 Swift 5 稍作调整,我得到了这个有效的代码。

if let stringA, !stringA.isEmpty {
    ...blah blah
}

Although I understand the benefits of creating an extension, I thought it might help someone needing just for a small component / package.虽然我了解创建扩展的好处,但我认为它可能会帮助那些只需要一个小组件/包的人。

When dealing with passing values from local db to server and vice versa, I was having too much trouble with ?'s and !'s and what not.在处理将值从本地数据库传递到服务器(反之亦然)时,我在处理 ? 和 ! 以及其他方面遇到了很多麻烦。

So I made a Swift3.0 utility to handle null cases and i can almost totally avoid ?'s and !'s in the code.所以我制作了一个 Swift3.0 实用程序来处理 null 情况,我几乎可以完全避免代码中的 ? 和 ! 。

func str(_ string: String?) -> String {
    return (string != nil ? string! : "")
}

Ex:-前任:-

Before :前 :

    let myDictionary: [String: String] = 
                      ["title": (dbObject?.title != nil ? dbObject?.title! : "")]

After :后 :

    let myDictionary: [String: String] = 
                        ["title": str(dbObject.title)]

and when its required to check for a valid string,当需要检查有效字符串时,

    if !str(dbObject.title).isEmpty {
        //do stuff
    }

This saved me having to go through the trouble of adding and removing numerous ?'s and !'s after writing code that reasonably make sense.这使我不必在编写合理有意义的代码后添加和删除许多 ? 和 ! 的麻烦。

Use the ternary operator (also known as the conditional operator, C++ forever! ):使用三元运算符(也称为条件运算符, C++ forever! ):

if stringA != nil ? stringA!.isEmpty == false : false { /* ... */ }

The stringA! stringA! force-unwrapping happens only when stringA != nil , so it is safe.强制解包仅在stringA != nil时发生,因此是安全的。 The == false verbosity is somewhat more readable than yet another exclamation mark in !(stringA!.isEmpty) . == false冗长比!(stringA!.isEmpty)另一个感叹号更具可读性。

I personally prefer a slightly different form:我个人更喜欢稍微不同的形式:

if stringA == nil ? false : stringA!.isEmpty == false { /* ... */ }

In the statement above, it is immediately very clear that the entire if block does not execute when a variable is nil .在上面的语句中,很明显,当变量为nil时,整个if块不会执行。

helpful when getting value from UITextField and checking for nil & empty stringUITextField获取值并检查nilempty字符串时很有帮助

@IBOutlet weak var myTextField: UITextField!

Heres your function (when you tap on a button ) that gets string from UITextField and does some other stuff这是您的函数(当您点击button ),它从 UITextField 获取字符串并执行其他一些操作

@IBAction func getStringFrom_myTextField(_ sender: Any) {

guard let string = myTextField.text, !(myTextField.text?.isEmpty)!  else { return }
    //use "string" to do your stuff.
}

This will take care of nil value as well as empty string.这将处理nil值以及empty字符串。

It worked perfectly well for me.它对我来说非常有效。

In my opinion, the best way to check the nil and empty string is to take the string count.在我看来,检查 nil 和空字符串的最佳方法是获取字符串计数。

var nilString : String?
print(nilString.count) // count is nil

var emptyString = ""
print(emptyString.count) // count is 0

// combine both conditions for optional string variable
if string?.count == nil || string?.count == 0 {
   print("Your string is either empty or nil")
}

Swift 5.4斯威夫特 5.4

extension Optional where Wrapped: Collection {
  var isEmptyOrNil: Bool {
    guard let value = self else { return true }
    return value.isEmpty
  }
}

Usage:用法:

var name: String?
name.isEmptyOrNil //true
name = "John Peter"
name.isEmptyOrNil //false

你可以使用这个功能

 class func stringIsNilOrEmpty(aString: String) -> Bool { return (aString).isEmpty }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM