Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if multiple Strings are empty or nil with "if" condition

Tags:

swift

What is the proper syntax for chaining multiple conditions within Swift if statement, like so:

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

or:

if (string1.isEmpty && string2.isEmpty) {}
like image 863
smisiewicz Avatar asked Sep 10 '26 02:09

smisiewicz


1 Answers

There's no need to use () around the two conditions:

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

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

Also, checking if a String is nil is not the same as checking for the emptiness of the string.

In order to check if your Strings are nil, they would have to be Optionals 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 unwrapping:

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

In this case, both Strings where not nil but could still be empty, so you could check for that too:

if let firstName = name1, secondName = name2 where !firstName.isEmpty && !secondName.isEmpty {
    println("\(firstName) and \(secondName) are not nil and not empty either")
}
like image 51
Eric Aya Avatar answered Sep 11 '26 20:09

Eric Aya