I am Jack’s fruitless aspiration

I am Jack’s fruitless aspiration

Using NSSpellChecker in Swift for Smart Quote check

I was trying to update straight quotes ' to the curly ones more often seen in text. NSSpellChecker offers that possibility among other options. It was difficult to find the necessary help online and even after I found something just had to experiment a lot.

Here's what worked for me:

import Foundation
import AppKit

let input = "What's up? \"How was he?\" How to fix these quotes?"
let correctedText =
    NSSpellChecker.shared.check(input, range: NSRange(0...input.count - 1), types: NSTextCheckingAllSystemTypes, options: nil, inSpellDocumentWithTag: 0, orthography: nil, wordCount: nil)
    .filter({$0.resultType == NSTextCheckingResult.CheckingType.quote})
    .reduce(input, { text, checkResult in
        text.replacingCharacters(in: Range(checkResult.range, in: text)!, with: checkResult.replacementString!)
    })

print("Corrected: \(correctedText)")
print("Original: \(input)")

The output from the app

Corrected: What’s up? “How was he?” How to fix these quotes? 
Original: What's up? "How was he?" How to fix these quotes?
 
Share this
Proudly part of