Swift Closure Compiler Error - ios

The following code:
var index = 0;
for (uuid, type) in map! {
{ (idx) in /*COMPILER ERROR HERE*/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
Dashlet.build(self.selectedDashboard!.getUuid(), dashletUuid: uuid, type: type) { (dashlet: Dashlet) in
self.dashlets![idx] = dashlet;
dispatch_async(dispatch_get_main_queue(), {
var path = NSIndexPath(forRow: idx, inSection:0);
self.tableView.reloadRowsAtIndexPaths([path], withRowAnimation: UITableViewRowAnimation.Automatic);
});
};
});
} (index);
index++;
}
but this results in a compiler error:
Cannot convert the expression's type 'Int' to Void
My wish is to call the dispatch_async as many times as there are entries in the dictionary, and each time with index being one greater than the last time.
EDIT:
Screenshot of actual simplified situation:

This seems to be triggering a compiler bug and/or crash in Xcode 6.0.1 and Xcode 6.1 GM (although it manifests itself slightly differently in each). The way to get around it is to explicitly define the complete closure type.
Instead of:
{ (idx) in
it would be:
{ (idx: Int) -> Void in
Update:
The radar I filed for this rdar://18571392 back in October was just closed; the compiler crash is fixed in Swift 1.2 / Xcode 6.3 beta 1 (6D520o).

Related

EXC_BAD_ACCESS for arrays in Xcode function

I have this function
func pickAttraction(attractionType: Array<Attraction>) -> Attraction {
let randAttr = attractionType[5]
if favoritesNames.contains(randAttr.attractionName) {
return pickAttraction(attractionType: attractionType)
} else {
return randAttr
}
}
and my program crashes (sometimes) on the line starting with "if favoritesNames". On the last time it crashed, the array favoritesNames had 1 string inside, and randAttr.attractionName had a different string. I expected it to return randAttr, but it crashed instead. Does anyone have any idea why?
I also tried
if favoritesNames.contains(randAttr.attractionName) || favoritesNames[0] == randAttr.attractionName {
and I got the same error
I've also tried
func pickAttraction(from attractions: [Attraction]) -> Attraction? {
attractions.filter { !favoritesNames.contains($0.attractionName) }
.randomElement()
}
instead of the other function and I still get the same error
Thank you
I believe let randAttr = attractionType[5] is accessing an index that doesn't exist. Can you verify that there is available data if you access the array at [5]?

Xcode 11.4: performSelector getting The LLDB RPC server has crashed

I have a problem with Xcode 11.4 using Swift 5.2 when trying to get value of func when performing a selector. This just occurred with a function that returns a Number or Bool type. That is my code:
if returnReadableType == "NSInteger" {
let c: NSObject.Type = cls as! NSObject.Type
if let performValue = c.perform(originalSelector)?.toOpaque() {
let originalResponse: Int = Int(bitPattern: performValue)
configDataResult[name] = originalResponse
}
} else if returnReadableType == "BOOL" {
let c: NSObject.Type = cls as! NSObject.Type
if let performValue = c.perform(originalSelector)?.toOpaque() {
let originalResponse: Bool = Bool(truncating: Int(bitPattern: performValue) as NSNumber)
configDataResult[name] = originalResponse
}
}
To explain the code, I try to perform an selector to get the value of it for swizzling them in the runtime. Because I don't know how much computed properties in a class will be declared, so I used the class_copyMethodList method to get all the method in cls. Then using some trick to determine the return type - returnReadableType, (in string) of each method. With the returnReadableType are BOOL or NSInteger, I got a crash when performed the selector. The crash log is:
Message from debugger: The LLDB RPC server has crashed. The crash log is located in ~/Library/Logs/DiagnosticReports and has a prefix 'lldb-rpc-server'. Please file a bug and attach the most recent crash log.
This did not occur in the < Xcode 11.4. I have researched the issue but do not reach any solution or any problem like that. Have anyone got the same issue? And how I can solve this issue?

Calling Wrapper Function From Javascript is Crashing App - React-Native

Hello I am trying to call a function in javascript that I am exporting via Objective C. When I call my function in javascript my app is crashing.
RCT_EXPORT_METHOD(getModelAsync:()
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSError *error;
NSString *contents = [[UIDevice currentDevice] model];
if (contents) {
resolve(contents);
} else {
reject(#"Test", #"Something is broken",error);
}
}
Its failing on this on the if statement with this Error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
if (!RCTIsIdentifierHead(**input)) {
return NO;
All help is welcome, thanks!
I came across this issue today and managed to solved it. It looks like the function argument types aren't matching up. This error seems to be triggered, when the function types aren't compatible. Something like the following code snippet, would trigger this error, because a dictionary is not compatible with type string and thus the function argument cannot be correctly cast.
Module.m
RCT_EXTERN_METHOD(myFunction: (NSDictionary)options)
Module.swift
#objc
func myFunction(_ options: String) -> Void {
...
}
To fix it, make sure you are doing something like this:
FixedModule.m
RCT_EXTERN_METHOD(myFunction: (NSDictionary)options)
FixedModule.swift
#objc
func myFunction(_ options: NSDictionary) -> Void {
...
}
I hope this helps!

Generic Swift struct: Segmentation fault: 11

I am trying to implement a struct with generic type that conforms to Hashable protocol. Can anybody help me understand why am I getting "Segmentation fault: 11" error with the following code.
I would really appreciate any insights regarding this.
struct Pmf<Element: Hashable> {
typealias Distribution = [Element : Float]
fileprivate var normalized = false
fileprivate var distribution:[Element : Float] = [ : ] {
didSet {
self.normalized = false
}
}
}
extension Pmf {
init(values: [Element], withProbs probs: [Float]) {
for pair in zip(values, probs) {
self.distribution[pair.0] = pair.1
}
}
var probDist: Distribution {
mutating get {
if !normalized {
self.normalize()
}
return self.distribution
}
}
subscript(value: Element) -> Float? {
mutating get {
if !normalized {
self.normalize()
}
return self.distribution[value]
}
set(prob) {
self.distribution[value] = prob
}
}
mutating func normalize() {
for (key, val) in self.distribution {
self.distribution[key] = val / Float(self.distribution.count)
}
}
}
var pp = Pmf<String>()
pp["One"] = 4
pp["Two"] = 5
pp["three"] = 5
print(pp)
Seems you need a little trick to define an initializer for a value type in an extension:
Add one line to your init(values:withProbs:) as shown below:
init(values: [Element], withProbs probs: [Float]) {
self.init() //<-
for pair in zip(values, probs) {
self.distribution[pair.0] = pair.1
}
}
Anyway compilers should not crash with SegFault 11. Even if the source code has some fault in it.
You'd better send a Bug Report to Apple, or to swift.org.
I starting writing a bug report for the similar situation (adding method deceleration using a generic with an associated type) and was getting segmentation faults every possible combination I tried.
I started to write a 'Minimum Verifiable Example' in a playground and found I couldn't replicate the fault.
The only difference between app and playground was that app had protocol and method in different source files.
I combined the two source files and no more segmentation fault!!
This took hours of my time to track down, hope it helps someone else.
Update: Submitted a bug for this fault, if you're encountering this too, please add a comment to let the team know you've encountered it: https://bugs.swift.org/browse/SR-3595

Xcode swift failed with exit code 254

I am getting this compiler error in my code and I can't figure out why:
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
The error is showing up somewhere in the following code segment:
var animalViewToSwap: AnimalView = animalViewMatrix.objectAtRow(0, andColumn: 0) as AnimalView
var currentRow = 0
var currentColumn = 0
var animalToSwapWith = true
var currentLocation = animalViewMatrix.findLocationOfObject(animalView)
currentRow = Int(currentLocation.row) - 1
currentColumn = Int(currentLocation.column) - 1
var rowDisplacement = 0
var columnDisplacement = 0
switch inDirection{
case "left":
columnDisplacement = withDistance * -1
if (Int(animalViewMatrix.columns) > currentColumn + columnDisplacement)&&(currentColumn + columnDisplacement >= 0)&&(animalViewMatrix.objectAtRow(CInt(currentRow), andColumn: CInt(currentColumn + columnDisplacement)) is AnimalView)
{
animalToSwapWith = true;
}
else { animalToSwapWith = false }
default:
println("error")
animalToSwapWith = false
break
}
(I have more cases that are very similar and am leaving them out for simplicity - the bug isn't in them)
First Error
One bug is in the line: animalToSwapWith = falseand if I set it to true and comment all the rest out besides the variable initialization lines the error goes away. Also if I comment all of it out but instantiate animalToSwapWith to false the error occurs even though it doesn't when it is instantiated to true.
Second Error
There is a second error in the line:if (Int(animalViewMatrix.columns) > currentColumn + columnDisplacement)&&(currentColumn + columnDisplacement >= 0)&&(animalViewMatrix.objectAtRow(CInt(currentRow), andColumn: CInt(currentColumn + columnDisplacement)) is AnimalView) In this line all of these methods have been called earlier in the file with variables of the same types above so knowledge of the methods shouldn't matter.
Conclusion
Is there a reason why these two errors are occurring or is it because swift and Xcode-6 are still in beta testing and it is a bug in Xcode? Also note that when commenting the two errors out from each other one at a time the error message is the same.
This is a Swift compiler bug, apparently testing for two or more implicitly unwrapped optionals causes the compiler to crash under some/many circumstances. Use Apple's Bugreporter to file this issue, mark it as duplicate of rdar://17212295.
Example
Here's a minimal example that crashes with the same error:
let a: String!
let b: String!
if a && b {
println("have both")
}
Compile on command line as follows and witness the same crash:
$ xcrun swift -v -g crash.swift
I was getting the same error and I tracked it down to this: I was extending NSError and in the extension was defining an enum. Moving the enum definition out of the extension fixed the error.
extension NSError {
enum WYBErrorCodes: Int {
case Fatal = 1000
case XmlParse = 1100
case CoreData = 1200
}
[...]
}
I'm getting the same error when adopt NSTextViewDelegate protocol for my class. If I remove that protocol, compilation goes fine. Strange indeed.
For the sake of providing other possible causes and how to fix them; I was trying to set the region of a map view within in dispatch block. If I commented out the setting of the region, the error goes away.
dispatch_once(&centerMapLocation, {
// var theSpan: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
// var theRegion: MKCoordinateRegion = MKCoordinateRegionMake(manager.location.coordinate, theSpan)
// self.map.setRegion(theRegion, animated: true)
})
}
I am getting this same error when I try to extend NSArray to have a foreach method:
extension NSArray {
func foreach(f: (AnyObject -> ())) {
for elem in self {
f(elem)
}
}
}
It would appear that extending NSArray with func that takes a function argument will cause the same problems. I worked around the issue by defining a forEachInArray function that takes the NSArray as an argument:
func forEachInArray<T>(array: NSArray, f: (AnyObject -> ())) {
for elem in array {
f(elem)
}
}
In my case, i was calling an objective-c function from swift through bridge. Signature was like -
- (SomeReturnType *)getSomething:(SomeOptions *)options
success:(void (^)(NSArray *response))success
failure:(void (^)(NSError *error))failure;
From swift, i was calling it as follows and getting compile error as "Xcode swift failed with exit code 254" -
ObjCClass().getSomething(nil, success: {(response : Array!) in
}, failure: {(error: NSError!) in
})
changing it to following worked for me -
ObjCClass().getSomething(nil, success: {(response : [AnyObject]!) in
}, failure: {(error: NSError!) in
})
I had this error and the bug was solved in Beta 7 available online today.

Resources