Swift: using NSDataDetectors

I am trying to port some Obj-c code and have problems creating NSDataDetector.

In Objective-C, I would do the following:

NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; 

From the documentation I have to do this:

 let linkDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Link, error: &error) 

But I get a compiler error: "NSTextCheckingType" does not convert to "NStextCheckingTypes"

If try this:

 let linkDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingTypes(), error: &gError) 

However, it passes, I get an exception at runtime:

 [NSDataDetector initWithTypes:error:]: no data detector types specified' 

Not sure if this is a mistake or not.

Thanks.

+8
swift
source share
4 answers

NSTextCheckingTypes to type UInt64; use the rawValue property on NSTextCheckingType to convert it.

 let ld = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: nil) 
+15
source share

The davextreme solution returns an error in Xcode 6.1 (6A1046a).

The 'fromRaw' method has been replaced by the 'rawValue' property

The new syntax uses rawValue instead of toRaw() as follows:

 let ld = NSDataDetector(types:NSTextCheckingType.Link.rawValue, error: nil) 
+9
source share

The jatoben solution returns an error in beta 4:

'NSTextCheckingType' does not have a name with a name

Changing this parameter to toRaw() resolves this:

 let ld = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Link.toRaw(), error: nil) 
+6
source share

Working solution for Swift 4:

 let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) 

Apple Docs Link: https://developer.apple.com/documentation/foundation/nstextcheckingresult.checkingtype/1411725-link

0
source share

All Articles