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.
NSTextCheckingTypes is typealiased to UInt64; use the rawValue property on an NSTextCheckingType to convert it.
let ld = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: nil)
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)
jatoben's solution returns an error in beta 4:
'NSTextCheckingType' does not have a member named value
Changing it to toRaw() resolves this:
let ld = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Link.toRaw(), error: nil)
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
As of Swift 5.7 you can do the following:
import RegexBuilder
let input =
"""
...
(Stackowerflow)
https://stackoverflow.com/questions/24345928/swift-using-nsdatadetectors
---
"""
let url = Reference(URL.self)
let regex = Regex {
Capture(.url(), as: url)
}
if let result = input.firstMatch(of: regex) {
print("URL: \(result[url])")
}
Related
There are several posts on this subject, but I can't see the answer to this problem in them. The following lines produce the title error:
let pdf_url = NSURL.fileURL(withPath: inputfile)
let pdf_doc = PDFDocument.init?(url: pdf_url) as! URL
I understand that the init method can take a variety of data types, but surely I've made it pretty clear that I want a URL.
Error message is:
error: ambiguous reference to member 'init(url:)'
A problem which may be related is that Xcode occasionally tells me to use URL, not NSURL, in the first line, but then complains that URL doesn't have the fileURL method.
(I also tried CGPDFDocument, but that wanted a CFURL, and wouldn't accept NSURL, even though they are supposed to be "toll-free bridged".)
The error occurs because you (try to) cast PDFDocument to URL.
You probably mean
PDFDocument.init?(url: pdf_url as! URL)
But the recommended Swift 3 syntax is
let pdfURL = URL(fileURLWithPath: inputfile) // returns a non-optional URL
let pdfDoc = PDFDocument(url: pdfURL)
Please use – Swift – camel case variable names rather than – javascript / php – snake case.
Use URL:
let pdf_url = URL(fileURLWithPath: inputfile)
I am working on an iOS app, and I just switched to Swift 3.0, so now I have a lot of errors in my code, and I'm not sure how to fix some of them.
1) Error "Argument labels '(fileURLwithPathComponents:)' do not match any available overloads" on the second line of this snippet:
let pathArray = [dirPath, recordingName]
let filePath = URL(fileURLwithPathComponents: pathArray)
2) Error "Cannot convert value of type '(CMAccelerometerData?,NSError?)->()
to expected argument type 'CMAccelermeterHandler' (aka ('Optional, Optional)->()')"
motionManager.startAccelerometerUpdates(to: OperationQueue.main) {
[weak self] (data: CMAccelerometerData?, error: NSError?) in self!.label.text = "started tracking"
Thanks to #Koen and #Larme, I found the solution to both of these:
1) let filePath = NSURL.fileURL(withPathComponents: pathArray)
2) should be just "Error" not "NSError"
I have code I've been using for SwiftyJSON and I'm trying to update to Swift 3 using XCode 8.0 Beta 3. I'm running into an issue where the compiler doesn't like the argument 'error: &err' as it did before. I've been searching for how to correctly pass an NSErrorPointer but everything I've found says to re-write, leave out the error and throw an error back. Since this isn't my code I'd rather leave it as it is. So what's the correct new way to use an NSErrorPointer?
var err : NSError?
// code to get jsonData from file
let json = JSON(data: jsonData, options: JSONSerialization.ReadingOptions.allowFragments, error: &err)
if err != nil {
// do something with the error
} else {
return json
}
The code above results in compiler error: '&' can only appear immediately in a call argument list. I've tried creating an NSErrorPointer so I can use that instead but I can't find anything on how to initialize one (the type alias declaration is not enough). I've already been to Using Swift with Cocoa and Obj-C, it does not contain the word NSErrorPointer, instead goes over the new way of throwing errors. I've also looked over a couple dozen posts all using the &err so apparently this is new to Swift 3.
Is there anyone out there that's solved this one? What's the answer to using NSErrorPointer?
Thanks,
Mike
That seems to be an error in the Swift 3 branch of SwiftyJSON at
https://github.com/SwiftyJSON/SwiftyJSON/blob/swift3/Source/SwiftyJSON.swift
which defines the init method as
public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer? = nil) {
do {
let object: AnyObject = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error??.pointee = aError
}
self.init(NSNull())
}
}
In the Swift 3 that comes with Xcode 8 beta 3, NSErrorPointer is an optional:
public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>?
as a consequence of
SE-0055: Make unsafe pointer nullability explicit using Optional
Therefore the error parameter should have the type NSErrorPointer,
not NSErrorPointer? (and consequently error??.pointee
changed to error?.pointee).
With these changes the init method becomes
public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error?.pointee = aError
}
self.init(NSNull())
}
}
and then your code compiles and runs as expected.
After I upgrade my Xcode to the latest version. It shows this error. Not sure what it means.
The ambiguous error occurs when the type of the object is AnyObject and the compiler has no idea whether the object can be key subscripted.
The solution is to cast result down to something suitable.
It seems to be a dictionary
if let dict = result as? [String:AnyObject] {
let userId = dict["id"] as! String
...
}
You have to define the result type, for example if this is a Dictionary try:
let dic: NSDictionary = result
let userId: String = dic["id"] as! String
I am trying to use the countForFetchRequest method on a managed object context in Swift 2.0.
I note that the error handling for executeFetchRequest has been changed across to the new do-try-catch syntax:
func executeFetchRequest(_ request: NSFetchRequest) throws -> [AnyObject]
but the countForFetchRequest method still uses the legacy error pointer:
func countForFetchRequest(_ request: NSFetchRequest,
error error: NSErrorPointer) -> Int
...and I am having a bit of trouble figuring out how to use this in Swift 2.0.
If I do the same thing as pre-Swift 2.0:
let error: NSError? = nil
let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
I get errors saying to remove the &, but if I remove that I get another error saying that NSError cannot be converted to an NSErrorPointer.
Any help would be appreciated about how to get this working.
Your code is almost correct, but error needs to be a variable, in order to be passed as
inout-argument with &:
var error: NSError? = nil
let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
Update: As of Swift 3, countForFetchRequest
throws an error:
do {
let count = try managedObjectContext.context.count(for:fetchRequest)
return count
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
return 0
}
You need to do like this:
let error = NSErrorPointer()
let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
print("Count \(fetchResults)")
This is the code for Swift 2.0