Xcode swift failed with exit code 254 - ios

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.

Related

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?

I don't understand why an Objective-C delegate function works and a Swift delegate function crash. Can you explain to me?

I have a framework built in Objetive-C. That framework is to connect and interact with a Bluetooth device.
In the demo code, the Objetive-C delegate function looks like. The demo code was provided by the creator of the framework.
-(void)babyScaleManagerScanDevices:(NSArray<ELBabyScaleDeviceModel *> *)babyScaleDevices{
NSLog(#"babyScaleManagerScanDevices = %#",babyScaleDevices);
ELBabyScaleDeviceModel *model = babyScaleDevices.firstObject;
}
I've included the framework in my swift project and imported the headers. I'm trying to obtain the same result by doing:
func babyScaleManagerScanDevices(_ babyScaleDevices: [ELBabyScaleDeviceModel]?) {
guard let device = babyScaleDevices?.first else {
print("Error unwrapping first device")
return
}
print("Device: \(String(describing: device))")
}
I get the following exception:
Thread 1: Precondition failed: NSArray element failed to match the Swift Array Element type
Expected ELBabyScaleDeviceModel but found ELPeripheralModel
Precondition failed: NSArray element failed to match the Swift Array Element type
Expected ELBabyScaleDeviceModel but found ELPeripheralModel: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1100.2.274.2/swift/stdlib/public/core/ArrayBuffer.swift, line 354
Inspecting babyScaleDevices array show:
babyScaleDevices [ELBabyScaleDeviceModel]? 1 value some
[0] ELPeripheralModel * 0x281cae100 0x0000000281cae100
This result is the same in the demo code in Objetive-C and my Swift project.
The class ELBabyScaleDeviceModel.h looks like:
#import "ELPeripheralModel.h"
NS_ASSUME_NONNULL_BEGIN
#interface ELBabyScaleDeviceModel : ELPeripheralModel
#end
NS_ASSUME_NONNULL_END
Can you explain me what is happening?
You have to specify Array to NSArray
Add this line to your code
let devices = babyScaleDevices as NSArray
You can try this
func babyScaleManagerScanDevices(_ babyScaleDevices: [ELBabyScaleDeviceModel]?) {
let devices = babyScaleDevices as NSArray
guard let device = devices.firstObject else {
print("Error unwrapping first device")
return
}
print("Device: \(String(describing: device))")
}
And after then check this -> Array vs NSArray
Try to change
func babyScaleManagerScanDevices(_ babyScaleDevices: [ELBabyScaleDeviceModel]?)
to
func babyScaleManagerScanDevices(_ babyScaleDevices: [Any]?)
and cast specific elements to ELBabyScaleDeviceModel, for example, in for.
It seems like the creator of this framework put ELPeripheralModel in the array instead of ELBabyScaleDeviceModel
I think its just the way that the code is bridged to Swift.
Could you try to specify the type as [ELPeripheralModel] and then cast it?
func babyScaleManagerScanDevices(_ babyScaleDevices: [ELPeripheralModel]?) {
guard let devices = devices = babyScaleDevices as? [ELBabyScaleDeviceModel],
let device = devices?.first else {
print("Error unwrapping first device")
return
}
print("Device: \(String(describing: device))")
}

canEvaluatePolicy Extra argument 'error' in call Swift Xcode 7

I work with Xcode 7 with swift and I would use the Touch Id. Only I have a error when I use canEvaluatePolicy. I understand my error, I call an argument too. Only if I do not call, it makes me a error because I did not manage my error ...
Here are my error and my code:
PS: sorry for my bad English.
Error : Extra argument 'error' in call
or
Error : Call can throw, but it is not marked with 'try' and the error is not handled
My code :
import Foundation
import UIKit
import LocalAuthentication
class touchid : UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var lblTouchId: UILabel!
override func viewDidLoad() {
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
#IBAction func authenticateWithTouchID(sender: AnyObject) {
let authenticationObject = LAContext()
self.pleaseWait()
if authenticationObject.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics) {
authenticationObject.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "Access", reply: {(Bool, authenticationError) in
if authenticationError != nil {
// Authentification annulé ou Touch id non disponible
self.lblTouchId.text = "annulé ou touch id non disponible"
self.clearAllNotice()
self.errorNotice("Erreur !")
}
else {
if Bool == true {
self.lblTouchId.text = "authentification réussi"
self.clearAllNotice()
self.successNotice("Succès !")
}
else {
self.lblTouchId.text = "echec de l'authentification"
self.clearAllNotice()
self.errorNotice("Erreur !")
}
}
}
)
}
}
}
As mentioned in Using Swift with Cocoa and Objective-C, all Objective-C methods that use NSError to return an error object will now throw when called from Swift 2.0, so you need to use:
do {
try method()
} catch let error as NSError {
reportError(error)
}
Removing the reference to NSError in the method() call.
Looking at Apple's documentation, something seems off. The method signature is:
func canEvaluatePolicy(_ policy: LAPolicy, error error: NSErrorPointer) -> Bool
The odd part is that currently, the method doesn't throw anything, so putting it in a do-try block isn't necessary. I don't know if (but my guess is that yes) this framework is still getting tweaked with Swift 2.0, but I thought I remembered it implementing throw at one point in the Xcode/Swift beta iterations. At one point the compiler was acting a little wonky and said that:
1 - the method signature only had 1 parameter, but implements throws (which it doesn't)
2 - But as mentioned above, when you do that, the compiler then gives you different errors.
One thing to point out is that the current method signature, as of this writing, has a second parameter which is an NSErrorPointer, not an NSError? object. Treat it like the current Apple docs suggest, so add something like:
var error: NSErrorPointer?
let canEvaluatePolicty = LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: error!)
And your code should compile. It might be a good idea to keep an eye on this framework as more iterations of the beta's come out.
Good Luck!
Although the answer from g_blott does indeed compile, it's not good practice to force unwrap when you're not sure what could happen.
This code also compiles, but doesn't force unwrap anything and handles the existence of an error:
var error: NSError?
let errorPointer: NSErrorPointer = NSErrorPointer(&error)
let canEvaluate = context.canEvaluatePolicy(.deviceOwnerAuthentication, error: errorPointer)
if let error = error {
print("Oh noes, an error! ", error)
} else if canEvaluate {
print("Can evaluate")
} else {
print("Can't evaluate")
}

Swift segmentation fault 11 due to variable scope

The following code caused the IDE in Xcode to fail, and swiftc throws segmentation fault (11):
func testDeviceWillNotify()
{
let expectation = expectationWithDescription("Will be ready.")
class FooMock: Foo
{
func accessoryDidConnect()
{
expectation.fulfill()
}
}
// ...
}
If I comment out the expectation.fulfill() everything is works correctly. I have also tried expectation! and expectation? but any reference to expectation caused Xcode to crash.
Using Xcode 6.1 (6A1052d) and its extremely frustrating. Does anyone know a way around this bug? Even writing the test another way will have to do.
I don't know how it your code suppose to work because the inner class have to automatically capture variables in the method scope.
This is a workaround
class FooMock: Foo
{
var accessoryDidConnectFunc : (Void -> Void)?
func accessoryDidConnect()
{
accessoryDidConnectFunc ?()
}
}
func testDeviceWillNotify()
{
let expectation = expectationWithDescription("Will be ready.")
let foo = FooMock()
foo.accessoryDidConnectFunc = { expectation.fulfill() }
// ...
}

Swift Closure Compiler Error

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).

Resources