Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Wildcard Matching Implementation in Swift

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Wildcard Matching runs in O(n*m) time and O(n*m) space, in Swift as in every other language.
  • ✓The Swift standard library has no glob type. Foundation gives you NSPredicate(format: "SELF LIKE %@", pattern), whose LIKE operator is exactly this grammar, '?' for one character and '*' for any run, with LIKE[c] for the case-insensitive form; you evaluate it with evaluate(with: name).
  • ✓Reviewers reject s[s.index(s.startIndex, offsetBy: i)] inside a loop and ask for a single Array(s.utf8) or Array(s) built once.
  • ✓The Swift trap: Swift's Character is an extended grapheme cluster and its comparison uses canonical equivalence, which changes what this algorithm means.
  • ✓Array(s) yields [Character], and Character wraps a String, so elements are not trivially copyable and every read can touch ARC retain and release traffic in the inner loop.

What Wildcard Matching actually is

Wildcard matching decides whether a whole string is described by a pattern in which '?' stands for exactly one character and '*' stands for any run of characters, including none. It is a full-string test, not a search: 'a*c' matches 'abbbc' but not 'xabbbc'. Engineers hit it writing file globs, log filters, ACL and route rules, and CDN purge patterns. The textbook solution is a dynamic-programming table dp[i][j] = 'does s[0..i) match p[0..j)', filled in O(n*m) time; a greedy two-pointer with one backtrack point is the usual production shortcut.

Wildcard Matching in Swift: what you actually reach for

The Swift standard library has no glob type. Foundation gives you NSPredicate(format: "SELF LIKE %@", pattern), whose LIKE operator is exactly this grammar, '?' for one character and '*' for any run, with LIKE[c] for the case-insensitive form; you evaluate it with evaluate(with: name). That route is Darwin-only in practice: swift-corelibs-foundation does not implement the predicate format parser, so NSPredicate(format:) traps on Linux. Because Swift links libc, fnmatch(3) is callable directly after import Darwin on Apple platforms or import Glibc on Linux. Modern Swift also ships the Regex type and String.wholeMatch(of:), which are the right target if you translate the pattern, though on Apple platforms they carry availability annotations you must gate on.

Swift implementation

Reviewers reject s[s.index(s.startIndex, offsetBy: i)] inside a loop and ask for a single Array(s.utf8) or Array(s) built once. They want the DP rows as ContiguousArray or a plain [Bool] swapped with the global swap(&a, &b), argument labels on the public entry point, and a throwing initialiser rather than a bool return if the pattern can be invalid. Force-unwrapping a pattern compiled from user input gets rejected outright.
swift
import Foundation

func isMatch(_ s: String, _ p: String) -> Bool {
    let sb = Array(s.utf8)
    let pb = Array(p.utf8)
    let m = pb.count
    let star = UInt8(ascii: "*")
    let quest = UInt8(ascii: "?")
    var prev = [Bool](repeating: false, count: m + 1)
    var cur = prev
    prev[0] = true
    for j in 1..<(m + 1) {
        prev[j] = prev[j - 1] && pb[j - 1] == star
    }
    for sc in sb {
        cur[0] = false
        for j in 1..<(m + 1) {
            let pc = pb[j - 1]
            if pc == star {
                cur[j] = cur[j - 1] || prev[j]
            } else {
                cur[j] = (pc == quest || pc == sc) && prev[j - 1]
            }
        }
        swap(&prev, &cur)
    }
    return prev[m]
}

// Foundation route, case-sensitive:
func glob(_ pattern: String, _ name: String) -> Bool {
    NSPredicate(format: "SELF LIKE %@", pattern).evaluate(with: name)
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Swift-specific trap

Swift's Character is an extended grapheme cluster and its comparison uses canonical equivalence, which changes what this algorithm means. A single '?' matches an entire family emoji built from several scalars joined by ZWJ, where the same '?' over s.utf8 would need eighteen bytes, and over s.utf16 eight code units: three different answers to 'how many ?' for one visible character. And a literal 'é' in the pattern matches an input written as 'e' plus U+0301, because the two are equal in Swift and unequal in every other language here. Decide which level you are matching at, spell it in the signature, and never mix Array(s) with s.utf8.count in the same DP.

Performance in Swift, beyond the O(n*m)

Array(s) yields [Character], and Character wraps a String, so elements are not trivially copyable and every read can touch ARC retain and release traffic in the inner loop. Array(s.utf8) yields [UInt8], which is trivial, removing that traffic entirely, and that single change usually dominates any tuning of the DP itself. The rows are copy-on-write: var cur = prev shares storage until the first write, and each mutation pays an isKnownUniquelyReferenced check. Bounds checks disappear under -Ounchecked, but that flag also removes arithmetic overflow traps, so most teams keep -O and hoist to withUnsafeMutableBufferPointer instead. The asymptotic cost is the same in every language, O(n*m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Wildcard Matching between languages.

Real-World Applications

Wildcard Matching applies wherever its problem shape appears in your own code. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Wildcard Matching helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Wildcard Matching appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Wildcard Matching over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Wildcard Matching to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

Frequently Asked Questions

Which Swift type or library should I use for Wildcard Matching?

The Swift standard library has no glob type. Foundation gives you NSPredicate(format: "SELF LIKE %@", pattern), whose LIKE operator is exactly this grammar, '?' for one character and '*' for any run, with LIKE[c] for the case-insensitive form; you evaluate it with evaluate(with: name). That route is Darwin-only in practice: swift-corelibs-foundation does not implement the predicate format parser, so NSPredicate(format:) traps on Linux. Because Swift links libc, fnmatch(3) is callable directly after import Darwin on Apple platforms or import Glibc on Linux. Modern Swift also ships the Regex type and String.wholeMatch(of:), which are the right target if you translate the pattern, though on Apple platforms they carry availability annotations you must gate on.

What is the most common Swift mistake when implementing Wildcard Matching?

Swift's Character is an extended grapheme cluster and its comparison uses canonical equivalence, which changes what this algorithm means. A single '?' matches an entire family emoji built from several scalars joined by ZWJ, where the same '?' over s.utf8 would need eighteen bytes, and over s.utf16 eight code units: three different answers to 'how many ?' for one visible character. And a literal 'é' in the pattern matches an input written as 'e' plus U+0301, because the two are equal in Swift and unequal in every other language here. Decide which level you are matching at, spell it in the signature, and never mix Array(s) with s.utf8.count in the same DP.

How does Wildcard Matching actually perform in Swift?

Array(s) yields [Character], and Character wraps a String, so elements are not trivially copyable and every read can touch ARC retain and release traffic in the inner loop. Array(s.utf8) yields [UInt8], which is trivial, removing that traffic entirely, and that single change usually dominates any tuning of the DP itself. The rows are copy-on-write: var cur = prev shares storage until the first write, and each mutation pays an isKnownUniquelyReferenced check. Bounds checks disappear under -Ounchecked, but that flag also removes arithmetic overflow traps, so most teams keep -O and hoist to withUnsafeMutableBufferPointer instead. Time complexity is O(n*m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.