Checking if multiple lines are empty or zero with "if" condition

What is the correct syntax to combine multiple conditions into a Swift if statement, e.g .:

if (string1!=nil && string2!=nil) {}

      

or

if (string1.isEmpty && string2.isEmpty) {}

      

+3


source to share


2 answers


There is no need to use ()

around two conditions:

let name1 = "Jim"
let name2 = "Jules"

if name1.isEmpty && name2.isEmpty {
    println("Both strings where empty")
}

      

Also, checking that a String is zero is not the same as checking that a string is empty.

To check if your strings are not null, they should have been optional in the first place.

var name1: String? = "Jim"
var name2: String? = "Jules"

if name1 != nil && name2 != nil {
    println("Strings are not nil")
}

      



And with safe sweep:

if let firstName = name1, secondName = name2 {
    println("\(firstName) and \(secondName) are not nil")
}

      

In this case, both lines where not zero, but can still be empty, so you can check this as well:

if let firstName = name1, secondName = name2 where !firstName.isEmpty && !secondName.isEmpty {
    println("\(firstName) and \(secondName) are not nil and not empty either")
}

      

+4


source


Zero checking and string content checking are different in Swift.

The NSString class uses a length method that returns the length of a string.

The rough Swift equivalent is the count () function. (It behaves differently for things like accented letters, but ignore that this time.

If you need an expression that will return 0 if String optional is nil or if it contains an empty string, use the following code:

var aString: String?

println(count(aString ?? ""))

aString = "woof"

println(count(aString ?? ""))

      

The code count(stringOptional ?? "")

will return 0 if the optional parameter is nil, or if it contains an empty string.

The double quote ??

is called the "Nile coalescing operator". It replaces the first part of the expression with the second part if the first part is nil. This is equivalent to:

string1 == nil ? "" : string1

      

You can use isEmpty with the same construct:



(string1 ?? "").isEmpty

      

And so your if statement would be better written as

if (string1 ?? "").isEmpty && (string2 ?? "").isEmpty 
{
  println("Both strings are empty")
}

      

Note that the above is only necessary if line1 and line2 are declared as optional:

var string1: String?

      

if they are declared as required String objects:

var string1: String

      

you don't need the extra syntax shown above and it won't compile.

0


source







All Articles