Swift 1.2 -> Swift 2 [closed] - ios

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm coding an app for my Kids. I have background in Java but havn't professionally coded in a decade. I don't thoroughly understand how the following line works but it worked in Swift 1.2:
leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
if (error != nil)
{
I need help translating this into working Swift 2.0 code. Could someone please post a translation of working Swift 2.0 code for the following method:
func getHighscores(leaderboardID: String) {
let leaderboardRequest = GKLeaderboard() as GKLeaderboard!
leaderboardRequest.identifier = leaderboardID
if leaderboardRequest != nil
{
leaderboardRequest.loadScoresWithCompletionHandler({ (scores:[AnyObject]!, error:NSError!) -> Void in
if (error != nil)
{
//println("error in alltimeHighscoreForLevel")
print(error.description)
self.updateLocalHighscore()
}
else
{
if(leaderboardRequest != nil){
if(leaderboardRequest.scores != nil ) {
if(leaderboardRequest.scores!.count > 0){
self.updateHighestForLevel(leaderboardRequest)
}
}
}
}
})
}
}

I think this will work for you:
leaderboardRequest.loadScoresWithCompletionHandler({ (scores, error) -> Void in
if let error = error {
// from here on your code should work
I think the definition of loadScoresWithCompletionHandler changed from the old code.

Two common ways to solve this:
Comment out the line / method which causes the error and start to retype it. The code completion will reveal the proper signature of the method. Then copy and paste the relevant code from the old line / method to the new one and resolve potential errors / warnings.
Press ⇧⌘0 and type (or copy&paste) the beginning of the method for example loadScoresWithCompletionHandler into the search field. This will take you to the documentation and you can see the whole declaration including the discussion.

Related

C in Swift Project [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I'm not too familiar with trying to use C functions from an external library in a Swift project.
I have the following code (commented with the necessary typedefs):
func sadp40() {
let start: Int32 = SADP_Start_V40(SadpDataCallBack, 0, nil) // <-- Error occurs here.
}
func SadpDataCallBack(lpDeviceInfo: SADP_DEVICE_INFO_V40?, pUserData: UnsafeMutableRawPointer) -> () {
// debugPrint(lpDeviceInfoV40?.struSadpDeviceInfo.szIPv4Address as Any)
}
/*
typedef void (CALLBACK *PDEVICE_FIND_CALLBACK_V40)(const SADP_DEVICE_INFO_V40 *lpDeviceInfo, void *pUserData);
CSADP_API BOOL CALLBACK SADP_Start_V40(PDEVICE_FIND_CALLBACK_V40 pDeviceFindCallBack, int bInstallNPF, void* pUserData);
*/
In the function sadp40() I'm receiving a Type of expression is ambiguous without more context error but I'm not sure how to fix it or why it is occurring.
Edit:
Option + Click in XCode:

How can I debug a "BUG IN CLIENT OF LIBPLATFORM: Trying to recursively lock an os_unfair_lock" crash?

I am writing a simple WKWebView extension that executes some Javascript and return the result as a Future.
func runJSFuture(_ js: String) -> Future<Any?, Error> {
Future<Any?, Error> { promise in
self.evaluateJavaScript(js) { (result: Any?, error: Error?) in
if let errorUnwrapped = error {
promise(.failure(errorUnwrapped))
return
}
promise(.success(result))
}
}
}
However, sometimes(consistently at a particular JS, but not all the time, so I figured it's not a problem with the JS itself) I get a crash as follows. I've been debugging and researching for a while and I've checked for implicitly unwrapped vars, force unwrapping. I'm stll unable to find the cause. There is not much useful information on the stack trace as well.
EDIT :
I've did some poking around converting the future to a PassthroughSubject and I have found where exactly the code in my question crashes. It'd comfort me if one could explain why/ how the crash happens and what I can do to avoid it or if this is a Combine bug.
func runJSFuture(_ js: String) -> AnyPublisher<Any?, Error> {
let pts = PassthroughSubject<Any?, Error>()
self.evaluateJavaScript(js) { (result, error) in
if let errorUnwrapped = error {
pts.send(completion: .failure(errorUnwrapped))
return
}
pts.send(result)
//pts.send(completion: .finished) // crashes here
}
return pts.eraseToAnyPublisher()
}
If I comment the line that crashes, the code works fine, but if I understand correctly, the pipeline would be open indefinitely? Any help would be extremely appreciated.

Implementing Swift 5.1 collection diffing in internal type

I'm building an iOS app that displays ranged iBeacons in a TableViewController.
To improve performances and test the new Swift 5.1 diffing feature I wrote the following code:
private func updateBeacons(_ rangedBeacons: [CLBeacon]) {
guard beacons != rangedBeacons else { return }
let difference = rangedBeacons.difference(from: beacons)
// Also tried:
// let difference = rangedBeacons.difference(from: beacons, by: { $0.uuid == $1.uuid })
// ...
}
When this code is reached a fatalError is thrown:
Fatal error: unsupported: file
/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1100.2.259.70/swift/stdlib/public/core/ArrayBuffer.swift,
line 231
How can I perform collection diffing on CLBeacons?
The referenced code can be found here:
https://github.com/apple/swift/blob/master/stdlib/public/core/ArrayBuffer.swift#L226-L232
I was hitting this issue as well, but in my case I was getting one of the arrays from a Core Data NSFetchedResultsController. I suspect it's related to the fact that the original array comes from Objective-C.
I was able to fix this by wrapping the arrays in a new Array:
private func updateBeacons(_ rangedBeacons: [CLBeacon]) {
guard beacons != rangedBeacons else { return }
let difference = Array(rangedBeacons).difference(from: Array(beacons))
// ...
}

how to retrieve the list of your application’s tiles already on the Microsoft Band 1

Im creating a Microsoft Band 1 application for iOS with Swift
This function on the documentation has me going cross eyed. Please help.
I know functions can act as types in Swift
i.e.
var exampleFunction: (String, Int) -> String
is a function that takes two parameters, a string and an int and returns a string.
The method I'm looking at says the following in Xcode (Swift language):
tilesWithCompletionHandler(completionHandler: (([AnyObject]!, NSError!) -> Void)!
which I believe is saying, titlesWithCompletionHandler takes in a parameter which is a function of type [AnyObject]!, NSError!) -> Void I'm not sure about the ()! surrounding the whole thing though I know this is forcing a value out of the optional.. thats hard to understand as well.
on the website for the documentation
it is written in Objective-c which shows this as the method definition:
[self.client.tileManager tilesWithCompletionHandler:^(NSArray *tiles, NSError *error) {
if (error){
// handle error
}}];
what I have attempted is to construct a function that is the type this is asking for:
//I had to create this function to match the parameter that the tilesWithCompletionHandler method required
func errorFunction(tileArray: [AnyObject]!, error: NSError!) -> Void {
print("hello")
if((error) != nil) {
//handle error
print("error was not nil, meaning an error occurred... :(")
}
else {
print("i got here")
self.tileArray = tileArray
}
}
then I created a type and assigned it to this function like so (which fixed the errors Xcode was griping about when I called the method Im trying to use):
let customFunction: (([AnyObject]!, NSError!) -> Void)! = errorFunction
the ()! part around the type still confuses me though
finally I call the function that I'm needing to call to get the tiles and pass in the function I just constructed
myBand.tileManager.tilesWithCompletionHandler( customFunction )
Edit: the error was not related to the problem. The print statements do print now, but I get into the error flow.
Am I going about this the right way?
Also, I'm trying to figure out how to handle the error part of the parameters. Do I need to use a
do {
try //some code I need to figure out what to write
} catch let error as NSError {
//code to handle error
}
There's just a lot going on in this method call for me to fully grasp. Any help would be much appreciated. Thank you for your time!
Your error handling seems to be correct in errorFunction. Just modify the print statement to also print the error object to see what the actual error is.
print("error was not nil, meaning an error occurred... :( \(error)")
You could further look at the error.code and add logic in your app to handle it. MSBErrorTypes.h has a list of possible error code and most likely your code will be in the 300 range.
After Larme's comment I was able to get it working with a closure in Swift.
I'm curious if the method I was using in my question would of worked...
This is what I did after updating my print statement that was suggested as well which let me learn you can print errors this way too! :
myBand.tileManager.tilesWithCompletionHandler( {(tiles:[AnyObject]!, error: NSError!) -> Void in
if((error) != nil) {
//handle error
print("Error in .tilesWithCompletionHandler: \(error)")
}
})
It's just a closure which apparently is equivalent to a block in Objective-c which I didn't really know about before now (the block part that is).
Thanks for the help everyone!

Updating to Xcode 7 Beta 5 & Swift 2 produced multiple errors

I updated Xcode to the new Xcode 7 beta 5. In doing so, it converted to Swift 2, but then created even more errors. Right now, I am completely stuck, and don't know what to do, because although all my errors are gone, my app will not work correctly.
My problem is this:
if(self.myOutput3 as? NSObject == true) {
print("IT IS TRUE")
PFUser.logInWithUsernameInBackground(self.myOutput1 as! String, password: "xxx") { (user: PFUser?, error: NSError?) -> Void in
if error == nil {
print("It Worked!")
// self.presentViewController(destViewController, animated: true, completion: nil)
let instillation = PFInstallation.currentInstallation()
instillation["user"] = PFUser.currentUser()
instillation.saveInBackgroundWithBlock(nil)
self.performSegueWithIdentifier("toTimeline", sender: self)
} else {
// self.enterButton.enabled = false
self.errorAlert()
print("Couldn't log in...")
}
}
} else {
print("IT IS FALSE")
self.performSegueWithIdentifier("continueTheSignIn", sender: self)
// self.move()
}
The program will perform the toTimeline segue, but not the continueTheSignIn . I don't see any logical reason that this is not working. Could anyone point me in the right direction?
Also, I am having an error in my messages feature.
cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:cell.textView!.textColor]
This is giving me the error "Cannot assign a value of type '[String : UIColor?]' to a value of type '[String: AnyObject]!'
I was not previously getting this error in Swift / Xcode 6.4, so I don't know how to fix it.
Additionally, once I bypass this to get into my app to see if my other features are working, most of my UITableViews are not displaying any information. One is, however the rest load the correct amount of rows, but display nothing. What could this be? Also, no Parse pictures are being displayed correctly either. These are even more concerning than the other problems...
Here is the picture after I deleted and re added the segue under a diff. name.
Parse wont support the beta version . it needs a full version . I have contacted them based on a similar issue . They said they will update the parse to work with xcode7 once the full version of xcode7 is released.

Resources