咨询NSTextCheckingKey的定义与使用:文档稀缺且遇代码困惑
addressComponents Case Hey there, let's clear up the confusion around NSTextCheckingKey—it's definitely one of those Foundation types with sparse official docs, so I get why you're stuck. Let's break this down step by step.
What is NSTextCheckingKey?
NSTextCheckingKey is a Foundation framework type that acts as a type-safe wrapper for string keys, specifically designed to work with NSTextCheckingResult (the output from text detection tools like NSDataDetector).
Think of it as a standardized way to access the sub-components of detected text (like parts of an address, phone number, or URL) without relying on error-prone string literals. It eliminates typos and gives you compile-time safety when pulling specific details from text detection results.
How to Use NSTextCheckingKey
Here's a practical walkthrough of using it in a common text detection workflow:
1. First, Detect Text with NSDataDetector
Start by using NSDataDetector to scan your text for a specific type (like addresses, links, or phone numbers):
let inputText = "Grab coffee at 789 Pine Rd, Chicago" let addressDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.address.rawValue) let detectionResults = addressDetector.matches( in: inputText, range: NSRange(inputText.startIndex..., in: inputText) )
2. Extract Components with Predefined NSTextCheckingKeys
Once you have a NSTextCheckingResult (specifically NSAddressCheckingResult for addresses), use the predefined NSTextCheckingKey values to pull out individual components:
if let addressResult = detectionResults.first as? NSAddressCheckingResult { let street = addressResult.addressComponents?[.street] let city = addressResult.addressComponents?[.city] let zipCode = addressResult.addressComponents?[.zip] print("Street: \(street ?? "N/A"), City: \(city ?? "N/A"), Zip: \(zipCode ?? "N/A")") }
Predefined keys include .street, .city, .state, .zip, .country, and more—all tailored to address components. For other detection types (like phone numbers), similar keys exist where relevant.
3. Create Custom NSTextCheckingKeys (If Needed)
If you're building custom text detection logic and need unique keys, you can extend NSTextCheckingKey to add your own:
extension NSTextCheckingKey { static let customDeliveryNote = NSTextCheckingKey(rawValue: "CustomDeliveryNote") } // You can now use this key just like the system-defined ones
Breaking Down case addressComponents([NSTextCheckingKey: String]?)
That line you're seeing is almost certainly part of a custom enum that wraps NSTextCheckingResult types, or a switch case handling address detection results. Let's unpack it:
addressComponents: This is the enum case name, representing the set of components from an address detection result.[NSTextCheckingKey: String]?: The associated value is an optional dictionary where:- Keys are
NSTextCheckingKeyinstances (either system-defined or custom) - Values are the string values of the corresponding address components (e.g., "789 Pine Rd" for the
.streetkey)
- Keys are
Here's how you might see this used in context:
enum TextDetectionResult { case addressComponents([NSTextCheckingKey: String]?) case phoneNumber(String) case url(URL) } // Converting NSAddressCheckingResult to your custom enum func convertToCustomResult(_ result: NSTextCheckingResult) -> TextDetectionResult? { switch result.resultType { case .address: let addressDict = (result as? NSAddressCheckingResult)?.addressComponents return .addressComponents(addressDict) // Handle other types... default: return nil } } // Using the custom enum if let customResult = convertToCustomResult(detectionResults.first!) { switch customResult { case .addressComponents(let components): let state = components?[.state] print("State: \(state ?? "N/A")") default: break } }
A quick note: Official docs are sparse because NSTextCheckingKey is a supporting type—most of its usage context is tied to NSDataDetector and NSTextCheckingResult, so you'll find more details in the docs for those classes (especially NSAddressCheckingResult's addressComponents property).
内容的提问来源于stack exchange,提问作者Chris Karani

