swift 3.0 syntax questions - swift

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"

Related

Cannot convert value of type 'MobileNetV2' to expected argument type 'VNCoreMLModel'

I'm currently building a new app and trying to integrate a Core ML model with Vision to my app... unfortunately, Xcode shows me this message: Cannot convert value of type 'MobileNetV2' to expected argument type 'VNCoreMLModel'
How may I solve this?
Here's my code below:
let config = MLModelConfiguration()
guard let coreMLModel = try? MobileNetV2(configuration: config),
let visionModel = try? VNCoreMLModel(for: coreMLModel.model) else {
fatalError("Couldn't load model!")
}
let classificationRequest = VNCoreMLRequest(model: coreMLModel, completionHandler: classificationCompleteHandler)
classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOption.centerCrop
visionRequests = [classificationRequest]
loopCoreMLUpdate()
}
This line shouldn't use coreMLModel but visionModel:
let classificationRequest = VNCoreMLRequest(model: coreMLModel, completionHandler: classificationCompleteHandler)

countForFetchRequest in Swift 2.0

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

DataReadingMappedIfSafe Error since Swift 2.0

Since Swift 2.0 ] get the following error executing this line of code in my GameViewController:
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
ERROR: "Type of expression is ambiguous without more context"
Replace with
NSDataReadingOptions.DataReadingMappedIfSafe
and remove last parameter:
NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
the call can throw and exception, enclose your call in
do {
let data = try NSData(contentsOfFile: path, options:NSDataReadingOptions.DataReadingMappedIfSafe)
}catch {
print("Error")
}

Error updating Swift 1 accelerometer code to Swift 2

I recently updated Xcode to version 7 which also includes Swift 2.
A lot of my code had errors and I managed to fix most of them except for one.
let manager = CMMotionManager()
if manager.accelerometerAvailable
{
manager.accelerometerUpdateInterval = 0.5
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue())
{ // **Error on this line**
[weak self] (data: CMAccelerometerData!, error: NSError!) in
buffer = data.acceleration.y
}
}
The resulting error is:
Cannot convert value of type '(CMAccelerometerData!, NSError!) -> ()' to
expected argument type 'CMAccelerometerHandler' (aka
'(Optional, Optional) -> ()')
How do I go about fixing this error so my code works with swift 2?
You dont need to declare the type of the block
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
[weak self] data, error in
buffer = data.acceleration.y
}
Try the following code.
let manager = CMMotionManager()
if manager.accelerometerAvailable
{
manager.accelerometerUpdateInterval = 0.5
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue())
{
data, error in
buffer = data.acceleration.y
}
}

Swift: Using NSDataDetectors

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])")
}