Check String for Nil & Empty

How do I test if a string is empty in Objective-C?

You can check if [string length] == 0. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

How to check Multiple string is not nil and not empty in swift 5?

You can add all Strings to an Array and call allSatisfy on that array.

func isSetupDone(token1: String?, token2: String?, token3: String?) -> Bool {
let tokens = [token1, token2, token3]
return tokens.allSatisfy { $0 != nil && $0?.isEmpty == false }
}

You can also merge the two conditions into a single one by optional chaining the optional strings, since $0?.isEmpty == false will evaluate to false in case $0 is nil.

func isSetupDone(token1: String?, token2: String?, token3: String?) -> Bool {
[token1, token2, token3].allSatisfy {$0?.isEmpty == false }
}

What is the best way to test for an empty string in Go?

Both styles are used within the Go's standard libraries.

if len(s) > 0 { ... }

can be found in the strconv package: http://golang.org/src/pkg/strconv/atoi.go

if s != "" { ... }

can be found in the encoding/json package: http://golang.org/src/pkg/encoding/json/encode.go

Both are idiomatic and are clear enough. It is more a matter of personal taste and about clarity.

Russ Cox writes in a golang-nuts thread:

The one that makes the code clear.

If I'm about to look at element x I typically write

len(s) > x, even for x == 0, but if I care about

"is it this specific string" I tend to write s == "".

It's reasonable to assume that a mature compiler will compile

len(s) == 0 and s == "" into the same, efficient code.

...

Make the code clear.

As pointed out in Timmmm's answer, the Go compiler does generate identical code in both cases.

How to check nil string in if condition swift

defTextView.text is empty String "" instead of nil.

Try where clause to check if it is empty:

@IBOutlet weak var defTextView = UITextView

@IBAction func btnTapped(sender: UIButton) {

if let definitionName = defTextView.text where !definitionName.isEmpty {

print(definitionName)

} else {

print("nil")

}
}

Check empty string in Swift?

There is now the built in ability to detect empty string with .isEmpty:

if emptyString.isEmpty {
print("Nothing to see here")
}

Apple Pre-release documentation: "Strings and Characters".

How to check if the string is empty?

Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:

if not myString:

This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:

if myString == "":

See the documentation on Truth Value Testing for other values that are false in Boolean contexts.



Related Topics



Leave a reply



Submit