Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Using NSDataDetectors

Tags:

swift

I'm trying to port some Obj-c code and having some trouble creating a NSDataDetector.

In Objective-C I would do this:

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

From the documentation I should be able to do this:

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

But I get a compiler error: 'NSTextCheckingType' is not convertible to 'NStextCheckingTypes'

If try this:

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

It passes however, I get a runtime exception:

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

Not sure if it's a bug or not.

Thanks.

like image 277
Miguelb Avatar asked Jun 21 '14 21:06

Miguelb


3 Answers

Working solution for Swift 4:

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

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

like image 102
Gaurav Singla Avatar answered Nov 09 '22 02:11

Gaurav Singla


NSTextCheckingTypes is typealiased to UInt64; use the rawValue property on an NSTextCheckingType to convert it.

let ld = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: nil)
like image 36
jatoben Avatar answered Nov 09 '22 01:11

jatoben


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

Method 'fromRaw' has been replaced with a property 'rawValue'

New syntax uses rawValue instead of toRaw() as follows:

let ld = NSDataDetector(types:NSTextCheckingType.Link.rawValue, error: nil)
like image 36
Max MacLeod Avatar answered Nov 09 '22 02:11

Max MacLeod