NSPredicate
NULL handling
blank strings
Swift programming
iOS development

NSPredicate to test for NULL, and blank strings

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

When you use NSPredicate against optional text fields, you often need to treat three cases differently: nil, an empty string, and a string that contains only whitespace. The correct predicate depends on whether you are filtering in memory or asking a backing store such as Core Data to translate the predicate into a fetch query.

Check for nil and Empty Strings First

The most direct predicate for "missing or empty" is:

swift
let predicate = NSPredicate(format: "email == nil OR email == ''")

That works well for common cases where email is optional and you want to match records with no value or an empty string.

You can use it in a fetch request:

swift
let request = NSFetchRequest<NSManagedObject>(entityName: "User")
request.predicate = NSPredicate(format: "email == nil OR email == ''")

Or for in-memory filtering:

swift
1let items: [[String: String?]] = [
2    ["email": nil],
3    ["email": ""],
4    ["email": "[email protected]"]
5]
6
7let predicate = NSPredicate(format: "email == nil OR email == ''")
8let result = (items as NSArray).filtered(using: predicate)
9print(result)

This is the simplest and most reliable starting point.

Handling Whitespace-Only Strings

Blank does not always mean empty. A value such as " " is not equal to '', but from a validation perspective it is usually still blank.

For in-memory filtering, a regex-based predicate is a practical solution:

swift
let predicate = NSPredicate(format: "email == nil OR email MATCHES '^\\\\s*$'")

The regular expression ^\\s*$ matches strings containing only whitespace or nothing at all.

This is useful when you are filtering Foundation collections in memory. It is also expressive, because you can clearly see that whitespace-only content is being treated as blank.

Core Data Needs More Care

When Core Data translates a predicate into SQL, not every string operation behaves the same way as in-memory evaluation. A simple equality check such as email == '' is widely safe. More advanced functions or regular expressions may not map cleanly depending on the store and the expression used.

A practical pattern is:

  • use the fetch predicate to eliminate obvious nil and empty values
  • trim whitespace in Swift when stricter validation is required

For example:

swift
1let request = NSFetchRequest<User>(entityName: "User")
2request.predicate = NSPredicate(format: "email != nil AND email != ''")
3
4let users = try context.fetch(request)
5let cleaned = users.filter { user in
6    !(user.email?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
7}

This keeps the database query simple while still enforcing the stronger "not blank after trimming" rule in application code.

Invert the Logic for Valid Strings

Sometimes the real requirement is not "find blank values" but "find strings that actually contain text." In that case, invert the predicate:

swift
let predicate = NSPredicate(format: "email != nil AND email != ''")

For in-memory checks where whitespace-only strings should count as blank, combine the fetch and a trim step or use a regex predicate when appropriate.

The important point is to be explicit about your definition of valid text. nil, "", and " " are different values even if the UI treats them all as "empty."

Common Pitfalls

The most common mistake is checking only for nil and forgetting that an empty string is still a non-nil value.

Another common issue is assuming that a whitespace-only string will match ''. It will not. If whitespace matters, trim or use a regex during in-memory filtering.

It is also easy to write one clever predicate and assume it behaves identically for Core Data fetches and array filtering. Simple equality checks are safer across both contexts than more advanced expression logic.

Summary

  • Use field == nil OR field == '' for the basic "null or empty" case.
  • Treat whitespace-only strings as a separate validation decision.
  • Regex predicates are useful for in-memory filtering when blanks include spaces or newlines.
  • Keep Core Data fetch predicates simple, then trim in Swift if needed.
  • Be explicit about whether you mean nil, empty, or whitespace-only text.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.