In Objective C, one could do the following to check for strings:
if ([myString isEqualToString:@\"\"]) {
NSLog(@\"m
You can also use an optional extension so you don't have to worry about unwrapping or using == true
:
extension String {
var isBlank: Bool {
return self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
extension Optional where Wrapped == String {
var isBlank: Bool {
if let unwrapped = self {
return unwrapped.isBlank
} else {
return true
}
}
}
Note: when calling this on an optional, make sure not to use ?
or else it will still require unwrapping.
What about
if let notEmptyString = optionalString where !notEmptyString.isEmpty {
// do something with emptyString
NSLog("Non-empty string is %@", notEmptyString)
} else {
// empty or nil string
NSLog("Empty or nil string")
}
if myString?.startIndex != myString?.endIndex {}