Reputation: 3004
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) {}
Upvotes: 3
Views: 4849
Reputation: 131418
Checking for nil and checking for string contents are different in Swift.
The NSString class has a length method that will return the string's length.
The rough equivalent in Swift is the count() function. (It behaves differently for things like letters with accent marks, but let's ignore that for now.
If you want an expression that will return 0 if a String optional is nil or if it contains an empty string, use code like this:
var aString: String?
println(count(aString ?? ""))
aString = "woof"
println(count(aString ?? ""))
The code count(stringOptional ?? "")
will return 0 if the optional is nil, or if it contains an empty string.
The ??
double-quote is called the "nil coalescing operator." It replaces the first part of the expression with the second part if the first part is nil. It's 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 needed if string1 and string2 are declared as optionals:
var string1: String?
if they are declared as required String objects:
var string1: String
you don't need the optional syntax shown above, and it won't compile.
Upvotes: 0
Reputation: 70098
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")
}
Upvotes: 6