I make Swept, a photo and video cleaner for iPhone and iPad. Its Find Duplicates screen groups near-identical photos so you can keep one and clear the rest. This post walks through how that works in the shipping code: Apple's Vision framework, a distance cutoff, a greedy loop, and a few limits worth stating up front.

Why not hash the files

A camera roll collects near-copies. Five shots of the same sunset because the first might be blurry. A burst. A photo that came back from a chat app, re-compressed, sitting next to the original.

A file hash only matches identical bytes. Re-encode a photo and the bytes change while the picture looks the same. Burst frames were never the same bytes to begin with. So hashing finds exact copies and misses most of the pile people want to clean. Swept compares what the photos look like instead.

Feature prints in one paragraph

Vision's VNGenerateImageFeaturePrintRequest turns an image into a VNFeaturePrintObservation: a vector of numbers describing what is in the picture, made by a model that runs on the device. You compare two prints with computeDistance(_:to:), and Apple's documentation sums up the rule in one line: "Shorter distances indicate greater similarity between feature prints." A comment in Swept's code describes the scale it works with as roughly 0 to 2. An exact copy lands at or near 0, a re-encoded copy or the next frame of a burst should land close to it, and unrelated photos land far away.

Here is the request as Swept runs it:

private nonisolated static func computePrint(_ cgImage: CGImage) async -> VNFeaturePrintObservation? { await withCheckedContinuation { continuation in DispatchQueue.global(qos: .userInitiated).async { let request = VNGenerateImageFeaturePrintRequest() request.imageCropAndScaleOption = .scaleFill let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) do { try handler.perform([request]) continuation.resume(returning: request.results?.first as? VNFeaturePrintObservation) } catch { continuation.resume(returning: nil) } } } } 

perform is synchronous, so the work goes to a global queue and comes back through a continuation. The main actor never runs the model.

Small images, cached prints

The print is made from a small image, not the original file. Swept asks PhotoKit for a 256 x 256 pixel version (PhotoKit target sizes are pixels, not points) with .opportunistic delivery and .fast resizing, and waits for the final, non-degraded result. Network access is allowed, so with iCloud Photos on, iOS may download a photo to produce that thumbnail.

Then the print is kept:

private var visionCache: [String: VNFeaturePrintObservation] = [:] private func visionPrint(for id: String) async -> VNFeaturePrintObservation? { if let cached = visionCache[id] { return cached } guard let image = await library.loadImage(for: id, targetSize: CGSize(width: 256, height: 256)), let cgImage = image.cgImage else { return nil } let print = await Self.computePrint(cgImage) if let print { visionCache[id] = print } return print } 

The cache is a plain dictionary keyed by the asset's local identifier. It lives in memory for as long as the service does, which is one scan. That turns out to be enough, because of how the grouping works.

Greedy grouping

The candidates arrive newest first. The loop takes the first one as a reference, measures its distance to everything left, puts everything within the cutoff into a group with it, and removes that group from the pool. Then it repeats with the next photo still in the pool. Trimmed (progress reporting removed):

var remaining = candidates // newest first var groups: [DuplicateGroup] = [] while !remaining.isEmpty { if Task.isCancelled { break } let reference = remaining.removeFirst() let matches = await similarity.rankSimilar(to: reference, among: remaining) { _ in } let duplicateIDs = matches.filter { $0.distance <= threshold }.map(\.id) if !duplicateIDs.isEmpty { groups.append(DuplicateGroup(identifiers: [reference] + duplicateIDs)) let dupeSet = Set(duplicateIDs) remaining.removeAll { dupeSet.contains($0) } } } 

The first pass computes a print for every candidate. Every later pass reads prints from the cache and only does distance math, which compares two vectors instead of running the model again. In the worst case, 1,200 photos with no duplicates at all, that is 719,400 distance calls, but the image decode and the model still run once per photo.

Inside rankSimilar, a failed comparison can't sneak a photo into a group, because the distance starts at the largest possible value:

var distance = Float.greatestFiniteMagnitude try? print.computeDistance(&distance, to: ref) matches.append(SimilarMatch(id: id, distance: distance)) 

Two properties of the loop shape the results. Groups are not transitive: a photo joins a group only if it is close to that group's reference. If A is close to B and B is close to C, but A and C are far apart, C waits for a later pass. That keeps groups tight, and it can split a long burst whose scene drifts into more than one group.

And the reference is always the newest photo in its group, which makes it the suggested keeper. The view model pre-marks every other member for Trash:

self.toTrash = found.reduce(into: Set<String>()) { set, group in set.formUnion(group.identifiers.dropFirst()) } 

That is a convenience, not a judgment about quality. More on that below.

Picking the cutoffs

Find Duplicates uses one fixed cutoff, 0.3. The comment above it says why: "strict, to avoid grouping merely similar shots." Because the screen pre-marks photos for Trash, a cutoff that is too loose costs more than one that is too tight. A missed duplicate wastes a little storage. A wrong group pre-marks a photo the user wanted to keep.

Find Similar answers a different question. You pick a reference photo or video, and what counts as "similar" depends on what you are looking for, so the user picks the cutoff:

enum Closeness: String, CaseIterable { case strict = "Strict", balanced = "Balanced", loose = "Loose" var threshold: Float { switch self { case .strict: return 0.5 case .balanced: return 0.85 case .loose: return 1.3 } } } 

Balanced is the default. The scan stores the distance of every candidate, and the control only filters that list, so moving from Strict to Loose is instant, with no second scan. A floor keeps the screen from coming back empty and a ceiling keeps it reviewable (minimumShown is 6, maximumShown is 120):

var displayedMatches: [SimilarMatch] { let under = allMatches.filter { $0.distance <= closeness.threshold } let chosen = under.count >= minimumShown ? under : Array(allMatches.prefix(minimumShown)) return Array(chosen.prefix(maximumShown)) } 

How were these numbers chosen? They are judgment calls. They have not changed since the code was first written in June, and there is no labeled test set behind them in the repo.

One thing Swept doesn't do yet, and you probably should: pin the request revision. Apple's documentation says a request uses the latest revision for the SDK your app links against, and picks up the new default when you recompile with a newer SDK. Cutoffs are tuned to one revision's distance scale, so a future revision could move them. Setting request.revision explicitly avoids that surprise.

Bounding the work

A print is cheap for one photo and not free for a whole camera roll. Three limits keep a scan reasonable:

  • Newest first, capped. Find Duplicates looks at the 1,200 newest photos that are not already in Swept's Trash. Find Similar checks the 1,500 newest items of the reference's type, photos with photos and videos with videos.
  • Off the main thread. The model runs on a global queue. Enumerating the library's identifiers is a nonisolated static function, so the background scan runs it in a detached task at .utility priority. The main actor holds the cache, does the distance math and updates progress.
  • Cancellable. Both loops check Task.isCancelled between photos, and Find Similar cancels the old scan when you pick a new reference.

The Duplicates card on Home can show "N to remove" before you open anything. That is the same scan, run in the background when Settings > Cleaning > "Auto-detect duplicates" is on (the default). It waits 1.5 seconds after Home appears, so launch and navigation settle first, and it only rescans when the number of photos outside the Trash has changed:

let candidates = all.filter { !trashed.contains($0) } let signature = candidates.count // Already up to date for this library state: nothing to do. if signature == self.lastSignature, self.count != nil { self.scanning = false return } 

A count is a cheap signature and an imperfect one. Delete a photo in the Photos app and take a new one, and the count is unchanged, so the card keeps its old number until something else moves it. The signature lives in memory, so a fresh launch always rescans.

The Simulator fallback

In the iOS Simulator the Vision request fails; the code comment records the error as "Failed to create espresso context". Rather than leave the feature broken there, the service probes Vision once and switches methods if it can't run:

// Probe Vision once on the reference; downgrade to pixel if it can't run. if method == .vision, await visionPrint(for: referenceID) == nil { method = .pixel } 

The fallback is a color layout. It asks PhotoKit for a 48 x 48 image, draws it into a 16 x 16 RGB grid and reads that out as 768 numbers. Two steps make those comparable:

// Mean-subtract (lighting invariance) then L2-normalize. let mean = v.reduce(0, +) / Float(v.count) for j in 0..<v.count { v[j] -= mean } let norm = sqrt(v.reduce(0) { $0 + $1 * $1 }) if norm > 0 { for j in 0..<v.count { v[j] /= norm } } 

Subtracting the mean removes a uniform brightness shift, and dividing by the length removes a uniform change in contrast. Every descriptor is then a unit vector, and the straight-line distance between two unit vectors is always between 0 and 2, the same rough scale the code assumes for Vision. So the same cutoffs still mean something. It is crude: it knows where the colors are, not what the picture shows. It exists so the feature works everywhere, the Simulator included.

Honest limits

  • The keeper is just the newest photo. No sharpness score, no "best shot" pick. You change it with "Keep only this" or by tapping photos to toggle them.
  • Photos only. Find Duplicates doesn't scan videos. Find Similar accepts a video as the reference and compares it with other videos.
  • The newest 1,200 only. Older duplicates sit outside the scan.
  • Nothing is deleted here. Marked photos move to Swept's Trash. They stay in your library, still using space, until you empty that Trash; then iOS asks for confirmation and they go to Recently Deleted in Photos for about 30 days. I wrote up how that Trash works in an earlier post.
  • No merge. The Photos app has its own Duplicates collection with a Merge button. Unlike Apple's, Swept does not merge metadata. It moves the extras to its Trash and leaves the keeper exactly as it was.

If you build this yourself

  • Make prints from small thumbnails and cache them by asset identifier, so grouping costs distance math, not model runs.
  • Set the cutoff by the cost of being wrong: strict where you pre-mark things for deletion, user-controlled where people are browsing.
  • Pin the request revision so an SDK update can't quietly move your cutoffs.
  • Keep a fallback on the same distance scale, so the feature still runs in the Simulator.

Disclosure: I make Swept, a free iPhone and iPad photo and video cleaner with ads; Swept Pro, a one-time purchase, removes them. All the scanning in this post runs on the device. Swept on the App Store: https://apps.apple.com/app/id6786665535?pt=128735707&ct=devto&mt=8

An AI assistant helped draft this article, working from the code it quotes.