Swift compiler error: segmentation fault: 11 on Archive - ios

When archiving my iOS app prior to submission for App Store release, I get an error that says
Command failed due to signal: Segmentation fault: 11
Then there's a huge block of paths and whatnot and at the end is a mention of a function that I have in the app. Here's the function:
func matrixOperationRequiresScalar(operation: MatrixOperation) -> Bool {
switch operation {
case .Addition, .Subtraction, .Multiplication, .Division, .Negative, .Determinant, .Inverse, .Transpose, .EigenOps: return false
case .ScalarMultiplication, .ScalarDivision, .Power: return true
}
}
You can tell that operation is an enum and all cases are covered here.
What can I do to fix this?

The switch you have in your code is missing the default case which is required in swfit. You can easily correct this :
func matrixOperationRequiresScalar(operation: MatrixOperation) -> Bool {
switch operation {
case .Addition, .Subtraction, .Multiplication, .Division, .Negative, .Determinant, .Inverse, .Transpose, .EigenOps: return false
case .ScalarMultiplication, .ScalarDivision, .Power: return true
default: return true
}
}
Source

Related

Xcode: swiftc failed with exit code 1

I have problem with this function:
func isSmallDevice() -> Bool {
if UIDevice().userInterfaceIdiom == .Phone {
if UIScreen.mainScreen().nativeBounds.height <= 1136 {
return true
}
}
return false
}
Basically if I comment these lines build will succeed and if not it will fail with following error:
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
No other errors or warnings are shown and note that I am not calling this function. I also tried quitting Xcode, deleting derived data and cleaning project.

Swift: Unit tests with functions that throw

How can one write unit tests in Swift that communicate useful information when calling functions that can throw?
What I'd really like to be able to do is something like this:
class TestTestsTests: XCTestCase {
func doFoo() throws -> String {
// A complex operation that might throw in various places
return "foo"
}
func doBar() throws -> String {
// A complex operation that might throw in various places
return "bar"
}
func testExample() throws {
let foo = try doFoo()
let bar = try doBar()
XCTAssertNotEqual(foo, bar)
}
}
Ideally the unit test runner would stop on the line where an unhandled exception occurred, and let the user explore the stack and error message. Unfortunately, adding throws to the test function causes it to be silently skipped over (and there's a UI bug that makes it look as though the test is still being run, and getting the same result as before adding throws).
Of course it is also possible to do this:
func testExample() {
let foo = try! doFoo()
let bar = try! doBar()
XCTAssertNotEqual(foo, bar)
}
But now a failure doesn't really provide the context we need. Add a throw to doFoo, and we get a message like fatal error: 'try!' expression unexpectedly raised an error: TestTestsTests.Error(): file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.1.101.15/src/swift/stdlib/public/core/ErrorType.swift, line 50, which only gives us the line number within testExample, and not within doFoo where the error occurred. This also seems to get the debugger 'stuck' (clicking continue just returns us to the same line with the same error message) on that line, regardless of whether breakpoints are enabled, and prevents other tests from running.
So maybe we could try something like this?
func testExample() {
do {
let foo = try doFoo()
let bar = try doBar()
XCTAssertNotEqual(foo, bar)
} catch {
XCTFail("\(error)")
}
}
This runs as expected, however we can't determine which of doFoo or doBar threw the error, and also no line number information. At least we can get the error message and not prevent other tests from running.
I could go on, but the short of it is that I can't find a way to simultaneously not break the unit test running (like with try!), figure out which function threw the error, and get the error information -- Unless I do something ridiculous like:
func testExample() {
var foo: String? = nil
var bar: String? = nil
do {
foo = try doFoo()
} catch {
XCTFail("\(error)")
return
}
do {
bar = try doBar()
} catch {
XCTFail("\(error)")
return
}
if let foo = foo, bar = bar {
XCTAssertNotEqual(foo, bar)
}
}
And I still don't get to find out where in doFoo or doBar the error occurred.
Is this just the sad state of unit testing in Swift, or am I missing something?
This runs as expected, however we can't determine which of doFoo or doBar threw the error, and also no line number information.
Maybe this is just an old problem or I'm not understanding your problem, or maybe you're just kind of making a statement rather than asking a question. But with respect to the quoted statement above, you can add any information you like to the messages in XCTest Assertions.
Swift also provides the following literals:
#file String The name of the file in which it appears.
#line Int The line number on which it appears.
#column Int The column number in which it begins.
#function String The name of the declaration in which it appears.
func testExample() {
var foo: String? = nil
var bar: String? = nil
do {
foo = try doFoo()
} catch {
XCTFail("try doFoo() failed on line: \(#line) in file: \(#file) with error: \(error)")
return
}
do {
bar = try doBar()
} catch {
XCTFail("try doBar() failed on line: \(#line) in file: \(#file) with error: \(error)")
return
}
if let foo = foo, bar = bar {
XCTAssertNotEqual(foo, bar)
}
}
If you really want to go crazy with it you can add error handling to your doBar() method and that error can contain any internal information you'd like.
In fact... by implementing your own errors in your methods you might not even need to separate the methods into two blocks in your tests, just printing the error should be enough. You can put any information you like in the error message.
Anyway, I think this is an outdated issue, you can get all the information you need from the test logs - they list out all the methods that failed and even have little arrows that let you jump right to the test that failed. They then highlight the specific assertion that failed... from there it's quite easy to tell what is happening in most cases. Worst case scenario you have to set a breakpoint or two and run the test again.
You can do your own errors, using Error or LocalizedError protocols
enum Errors: Error, CustomStringConvertible {
case foo_param_is_null
case bar_param_is_null(paramIndex: Int)
var description: String {
switch self {
case .foo_param_is_null:
return "Param is null in foo"
case .bar_param_is_null(let paramIndex):
return "Param at index \(paramIndex) is null in bar"
}
}
}
func foo(_ param: Int) throws {
guard param != 0 else {
throw Errors.foo_param_is_null
}
print("foo = \(param)")
}
func bar(_ params: [Int]) throws {
if let index = params.firstIndex(where: {$0 == 0}) {
throw Errors.bar_param_is_null(paramIndex: index)
}
print("bar = \(params)")
}
do {
try foo(1)
try foo(0)
} catch {
print("\(error)")
}
do {
try bar([1,2,3])
try bar([1,0,3])
} catch {
print("\(error)")
}
Result:
foo = 1
Param is null in foo
bar = [1, 2, 3]
Param at index 1 is null in bar
And if you need even more information, you can use structures to define errors and error domains. Something like :
struct FooBarError: Error, CustomStringConvertible {
var string: String
var context: Any?
static func fooError() {
FooBarError(string: "Foo Error")
}
static func barError(context: BarErrorContext) { FooBarError(string: "Bar Error", context: context)
}
var description: String {
if let cox = context as? BarErrorContext {
return "\(string) - paramIndex: \(ctx.paramIndex) - \(ctx.insidiousReason)"
}
return string
}
}
Note:
As #ibrust proposed, you can pass #function, #line and other special parameters to your errors initialisers to provide this information
do {
try foo()
} catch {
throw(BarFooError.foo(line: #line))
}
You can also propagate the original error
do {
try bar()
} catch {
throw(BarFooError.bar(exception: error))
}
Edited:
Finally , you can also use print(Thread.callStackSymbols) in your error description, but at this point, there is a risk of confusion between debugging and testing. Just a personal thought.

How can I access the associated values of SwiftyDropbox errors?

I’ve been working with SwiftyDropbox and I’m having a curious problem with errors. Specifically, I’m not sure how to manipulate errors in the closure callbacks provided after responses are received so that I can get at their associated values.
For instance, the completion handler for Dropbox.authorizedClient.filesListFolder provides a
CallError<(Files.ListFolderError)>?
to work with. How would I go about checking if it is a
CallError.HTTPError
, so that I can get the HTTP error code out of it? Right now I’m just sucking that information out of the error’s .description but that doesn’t seem like the right way to do it.
This is what I’ve tried. I suspect I’m failing to understand something with the generics involved.
client.filesListFolder(path: "", recursive: false).response({ (listFolderResult, listFolderError) -> Void in
switch listFolderError {
case let .HTTPError(code, message, requestId):
print("http error")
default:
print("not a http error")
}
Enum case 'HTTPError' not found in type 'CallError?'
The problem here is that we're trying to switch on an optional. This simpler example highlights the exact same problem:
enum Foo {
case a
case b
}
let x: Foo? = nil
switch x {
case .a:
print("a")
case .b:
print("b")
}
Enum case 'a' not found in type 'Foo?'
We can switch over optionals because Optional is itself an Enum, with two cases: None and Some(T).
So when we're switching over an optional, Swift expects some code like this:
switch someOptional {
case .Some(someValue):
print("do some things")
case .None:
print("someOptional was nil")
}
But that's probably not necessarily particularly useful to use. We have an optional enum, and ultimately, if we dealt with our optional in a switch, we'd just have nested switch statements. Instead, we should deal with our optional in the normal Swift way of dealing with optionals:
if let error = listFolderError {
switch error {
case let .HTTPError(code, message, requestID):
print("http error")
default:
print("some other error")
}
} else {
print("there was no error")
}

Segmentation fault when using toRaw()

Working on swift programming language. Using XCode 6.1 GM with iOS 8.1 Beta.
In 2 places inside code getting error message:
Method 'fromRaw' has been replaced with a property 'rawValue'. When I replace .toRaw() with .rawValue getting unknown compiler error.
if self._attached != nil && self._attached!.toRaw() == i {
continue
}
...
self._segmentPoints[direction.clockwise().toRaw()].0, self._segmentPoints[direction.counterclockwise().toRaw()].1)
What am I doing wrong? any suggestions on how to use .rawValue?
toRaw and fromRaw are cancel by new version of xcode
replace by "rawValue"
eg:
enum Rank: Int{
case Ace = 1
case Two,Three,Four
case Jack,Queen,King
func simpleDesc() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Jack
let aceRawValue = ace.rawValue
println(aceRawValue)
let b = Rank(rawValue: 5)
println(b!.simpleDesc())

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