104

Adding a (convenient) computed height property to UIView in my UIViewExtension.swift file is causing the Swift compiler to segfault... What could possibly be going wrong here?

0  swift                    0x00000001061e5608 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x00000001061e5af4 SignalHandler(int) + 452
2  libsystem_platform.dylib 0x00007fff894da5aa _sigtramp + 26
3  libsystem_platform.dylib 0xb03939841e997c88 _sigtramp + 2504775416
4  swift                    0x00000001064c8bb9 swift::NominalTypeDecl::getMembers(bool) const + 41
5  swift                    0x00000001055efab9 swift::irgen::ClassMetadataLayout<(anonymous namespace)::FindClassMethodIndex>::addClassMembers(swift::ClassDecl*) + 329
6  swift                    0x00000001055e97b2 swift::irgen::emitVirtualMethodValue(swift::irgen::IRGenFunction&, llvm::Value*, swift::SILType, swift::SILDeclRef, swift::CanTypeWrapper<swift::SILFunctionType>, swift::ResilienceExpansion) + 434
7  swift                    0x00000001056550d3 swift::SILVisitor<(anonymous namespace)::IRGenSILFunction, void>::visit(swift::ValueBase*) + 42611
8  swift                    0x000000010564a266 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 8678
9  swift                    0x00000001055cb6f8 swift::irgen::IRGenModule::emitGlobalTopLevel() + 184
10 swift                    0x00000001056376e3 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1859
11 swift                    0x0000000105638033 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
12 swift                    0x00000001055aa65a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 4842
13 swift                    0x00000001055a935d main + 1533
14 libdyld.dylib            0x00007fff8a82e5fd start + 1

 

1.  While emitting IR SIL function @_TFCSo6UIViewg6heightSd for 'anonname=0x7ff422892fd0' at <path redacted>/UIViewExtension.swift:60:5
<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

If more information is needed to crack this, just comment. Thanks!

Edit:

Here's a related .xcodeproj that returns this question's compiler error. Download here

Community
  • 1
  • 1
aleclarson
  • 18,087
  • 14
  • 64
  • 91
  • 7
    compilers shouldn't segfault. if this is a new issue, file a bug report. – Karoly Horvath Jun 14 '14 at 17:52
  • 3
    Looks like a compiler bug. You should report it to Apple so they can sort it out. – Chuck Jun 14 '14 at 17:52
  • 13
    The compiler has been segfaulting left and right as I have been migrating an Objective-C project to Swift. It's been disheartening to say the least. – aleclarson Jun 14 '14 at 17:56
  • 1
    @aleclarson I assume that the release version will work better, but if you find bugs, I'd report them since that may be the only way they'll get fixed before release. – Joachim Isaksson Jun 14 '14 at 18:11
  • 7
    I was wishfully thinking Swift was gonna be ready to use right out of the gate. Waiting sucks! :) – aleclarson Jun 14 '14 at 18:36
  • In exchange for having to report bugs on the crashers you frequently find in a pre-1.0 product, you get the opportunity to also file bugs about design directions or request features and enhancements. Enduring some inconvenience so that the final 1.0 product is not just better, but better *for you*, is what beta testing is all about. – rickster Jun 14 '14 at 19:00
  • It's a balancing act between progressing with my startup and planting a foundation for my future, heavy use of Swift. Not the easiest position to be in. – aleclarson Jun 14 '14 at 19:12
  • Here's a related `.xcodeproj` that returns this question's compiler error. [**Download here**](http://www.mediafire.com/download/9ic636luugmo6jd/SwiftCompilerSegFaultExample.rar) – aleclarson Jun 14 '14 at 19:13
  • Personal opinion, I wouldn't stake the future of my company on swift being ready for prime time this year. Go with the much safer objective-c. – David Berry Jun 15 '14 at 07:42
  • @David You think there's a high chance that Swift would be detrimental to my app, simply because it's a new language, or for other reason(s)? – aleclarson Jun 15 '14 at 15:03
  • I think there's a non-zero chance that there will still be significant issues with it come fall. Im in a similar position, and while I would love to use swift for a project with a hard fall release date, I can't justify the risk that it will impact the release schedule. Even more likely is that dealing with the issues on the way will impact my scheduling. – David Berry Jun 15 '14 at 17:01
  • @David Seems a tad paranoid. It's hard to imagine Apple screwing up badly enough that I can't just port some Swift back to Objective-C if absolutely required (since the two are interoperable in the same project). Perhaps I'm too optimistic? – aleclarson Jun 15 '14 at 17:05
  • And while some of the beta bugs have taken time to work around, I can still see Swift improving my development speed over just sticking with Objective-C. I could be wrong, I suppose. – aleclarson Jun 15 '14 at 17:06
  • This question appears to be off-topic because it is a bug report about beta software. File a report with Apple. – nobody Jun 15 '14 at 17:09
  • @AndrewMedico Possibly off-topic. It involves Swift and its compiler... and it's not always a bad idea to see if the StackOverflow community has found a workaround. I've filed a report already ([rdar://17315806](http://openradar.appspot.com/radar?id=5862932214710272)). :) – aleclarson Jun 15 '14 at 17:12
  • curious as to how everyones experience turned out, a year later. – Tyler Sep 18 '15 at 16:12
  • In my case, this was solved by doing a force clean (Cmd + Opt + Shift + K) and then rebuilding the project. – Josh at The Nerdery Sep 25 '15 at 16:20
  • Wow! Two years later and still this one. What a fail, Apple! – qwerty_so Jul 06 '16 at 12:27
  • Should I bother with installing Xcode 7.3.1? Or this error will persist nonetheless? – theDC Aug 21 '16 at 08:29
  • @DCDC Given my experience with the Swift compiler, up to and including iOS 8 - it still segfaults left and right. The slightest syntax issue is equally likely to result in a segfault or a useful error message. Pretty sad that we're now this far in and it's still functionally broken. – Colin M Aug 31 '16 at 18:07
  • It's 2018 and Xcode 9 still seg faults randomly :( – paulvs Oct 10 '17 at 19:11

54 Answers54

76

I had this error because I was doing this :

if(currentMeal?.State == .Deleted){

}

instead of

if(currentMeal!.State == .Deleted){

}

so I think optional not unwrapped in if condition can cause this error

Fjohn
  • 1,602
  • 14
  • 10
  • 3
    That was the cause for me too. But that was supposed to be correct right? It's only a compiler bug is it – DeFrenZ Oct 19 '14 at 18:33
  • Same. Optional enum check. Hope they fix it – mente Dec 18 '14 at 10:03
  • The correct code would be: if(currentMeal.State == .Deleted){} as Swift helpfully overloads == for two optionals that are equatable. Fjohn's post is quite dangerous. – mattyohe Jan 13 '15 at 01:14
  • 1
    It's about a compilation error, the code I past is dangerous if the variable is not verified before. what about your code if currentMeal is nil ? it's the same no ? could you explain me why my code is more dangerous than yours please ? swift take advantage of optional without using "?" ? – Fjohn Jan 14 '15 at 09:19
  • Thanks, this is my case too. Swift has been giving me unpleasant surprises all along the way, but this one is way over the limit. – CodeBrew Feb 15 '15 at 22:37
  • Instead of force unwrapping, I think the best approach would be to wrap it in an if let statement. – Kyle Redfearn Nov 04 '15 at 22:02
  • I was unable to build/run my app ... reverted changes ... but ya, this is due to syntax error in the outlined class, and there is no need to revert anything – Chris Allinson Oct 11 '16 at 01:49
28

When you run into a compiler segfault in Swift, you don't get a handy line number and error message. Here's how you can track the problem down:

  1. Create a new file called SegFaultDebugger.swift in your project.
  2. In this new file, define an extension to the class that's giving you problems.
  3. Move a group of methods from the main file to SegFaultDebugger.swift.
  4. Compile.

At this point, one of three things happens:

  • You still get the segfault in the original file: Move the methods from SegFaultDebugger.swift back to the original file and move a different set of methods into SegFaultDebugger.swift. Repeat
  • You get a segfault in SegFaultDebugger.swift: Great! Now use binary search to pin the segfault down to a specific method until you can figure out what construct is causing it.
  • You get meaningful compiler errors: Great! Fix the errors. Once everything compiles, move your methods back into the original file.
Bill
  • 44,502
  • 24
  • 122
  • 213
  • 2
    Thanks! This helped after hours of scratching my head. – dejavu89 Jan 30 '17 at 22:19
  • 2
    This was very useful! In my case, I had my NSFetchedResultsControllerDelegate in an extension and it was enough to merge that back to the main class block. – Mikael Grön Jun 23 '17 at 20:55
  • @MikaelGrön - can you expand on that? What exactly did you have in the extension? – RyanJM Dec 20 '17 at 18:14
  • But how do you know which class is the one giving you the issues? – the Reverend Nov 09 '18 at 01:14
  • @theReverend If you're not sure, you'll have to try each class in the offending file. But swiftc hasn't really had a segfault problem in a few years - not sure my answer is even relevant anymore. – Bill Nov 13 '18 at 17:52
  • This is not necessary anymore. In the error details Xcode now shows where it segfaults – Allison Nov 21 '18 at 06:48
12

I got this error while extending one of my protocols and mistyped and optional type argument.

protocol SomeProtocolName: class {
    var someProtocolVariable: String { get set }

    func someProtocolFunction(someProtocolVariable: String)
}

// MARK:
extension SomeProtocolName {
    func someProtocolFunction(someProtocolVariable: String?) {
        self.someProtocolVariable = someProtocolVariable
    }
}

The difference in function arguments String in prototype and String? in extension caused Segmentation Fault 11.

victor.vasilica
  • 1,491
  • 12
  • 14
  • 3
    I got this too. Looks like Apple has some issues with their optional typing. One major issue is when ! is used inside a variable type. It is non-optional by default, but the compiler gets confused. – user1122069 Feb 21 '16 at 23:32
  • @user1122069 agree, protocols have some issues left. Hope with next versions this issues will be fixed. – victor.vasilica Feb 23 '16 at 12:43
  • I wasn't talking about protocols, just in general. I just learned what ! does inside a variable, but the IDE and compiler often fail to get accurate errors for !. – user1122069 Feb 24 '16 at 14:57
  • @user1122069 my bad, sry. – victor.vasilica Feb 24 '16 at 16:18
  • This happened to me when adding lot of items in an array – aguilarpgc Mar 09 '16 at 16:58
  • @aguilarpgc it would be a good idea to add your own answer with more details about your particular case and the solution that worked for you. Other people may face the same issue as you and may find your answer useful. – victor.vasilica Mar 10 '16 at 13:23
  • @Simple Just remove "func someProtocolFunction(someProtocolVariable: String)" from the protocol and only leave it in the extension , that worked for me... – Ivelius Apr 11 '16 at 13:05
  • @Ivelius removing the `func` from protocol declaration would fix the issue but has different implications that may be not what you want. The point is not in how to fix it, I've provided a fix, but rather how *Segmentation Fault 11* may be caused by a small mismatch in declaration and extension that the IDE and compiler are not identifying properly. – victor.vasilica Apr 12 '16 at 08:46
9

I had this error too, and I fixed it like this:

Check your project and find out which files are used twice and remove one, or delete and re-add them all.

Errors in my Xcode:

:0: error: filename "AttributedString.swift" used twice: '/Users/.../CNJOB/CNJOB/AttributedString.swift' and '/Users/.../CNJOB/CNJOB/AttributedString.swift'

:0: note: filenames are used to distinguish private declarations with the same name

:0: error: filename "APIClient.swift" used twice: '/Users/.../CNJOB/CNJOB/APIClient.swift' and '/Users/.../CNJOB/CNJOB/APIClient.swift'

:0: note: filenames are used to distinguish private declarations with the same name

Command /Applications/Xcode 3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Pang
  • 9,564
  • 146
  • 81
  • 122
JNYJ
  • 515
  • 6
  • 14
9

In Xcode 7, you can click on the error in the Debug Navigator and you'll be shown an expanded view of the crashes. Clicking on the hamburger button on the right expands the error, and if you scroll all the way down to the bottom of the expanded error message, you will see where it comes from.

enter image description here

For me, I had two of those segmentation fault errors. In the picture above, the first one is what it looks like when collapsed, the second is when you expand the hamburger button. At the very bottom of the expanded gray box, you'll see a message that says where the compiler crashed.

Note however that the error message may at times be not informative enough, so while it tells you where it crashed, it doesn't always say why and how to fix it. Getting rid of this error is still very much a matter of guesswork.

Matthew Quiros
  • 13,385
  • 12
  • 87
  • 132
  • 1
    Was able to track down the errors from the Navigator. Thanks, this helped me fix my errors! – Vishal Mar 23 '16 at 04:20
5

I’ve discovered a simple workaround until the problem is fixed in a future Xcode/Swift build:

  • Simply place all extensions causing the issue in the .swift file that it’s being used.

In the example project you provided, place the contents of UIViewExtension.swift and CALayerExtension.swift above AppDelegate.swift

Hopefully this can get us to write working Swift code until the problem’s cleared up.

gomollon
  • 503
  • 3
  • 14
4

As for me, adding private to static var fixed clang crash:

private static var taskId = 0
Cfr
  • 5,092
  • 1
  • 33
  • 50
2

I had a compiler segmentation fault on a statement like this:

someFunction(isFlagged ? "String1" : "String2")

I just did a if-else statement instead and it works.

pojo
  • 5,892
  • 9
  • 35
  • 47
2

This typically happens when the compiler does not have enough information (despite what you think) to guarantee/determine the state of a statement or a variable within a statement.

For example, imagine you have a dictionary of type [String: String] which you populate with city names as keys and a comma separated list of corresponding zip codes/post codes.

Imagine that somewhere in your code you want to update the list of corresponding codes:

myDict[town] += newZipCode + ","

In this case, the compiler will respond with segmentation fault as town might not be in the dictionary and therefore it cannot guarantee that the above statement will have a valid value.

To resolve this, you should store the current state of myDict[town] in a separate variable allowing you to handle the case of key not in dict and then update the value for the given key:

myDict[town] = guaranteedValue + "," newZipCode + ","

Unfortunately, it is not always straightforward to determine the root cause so I hope this simple example helps.

zevij
  • 2,416
  • 1
  • 23
  • 32
2

You can also have this problem if you declare a condition with an unwrapped Bool as a property

Beninho85
  • 3,273
  • 27
  • 22
1

In my case, this error because I use Class name for variable

var MYClass : MYClass {
    get {
        return.....
    }
}

And this fixes my problem

var myClass : MYClass {
    get {
        return.....
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
aminhotob
  • 1,056
  • 14
  • 17
1

In my case, a misplaced colon during string interpolation broke mine (XCode 6.1.1).

Example:

println("\(value1:value2)") 

when I meant to do:

println("\(value1) : \(value2)")
jimejim
  • 594
  • 6
  • 8
1

This error happened to me when I tried to override weak variable from parent class.

In base class:

weak var stripeViewDelegate : StripeViewDelegate? = nil    

Derived class:

override weak var stripeViewDelegate : StripeViewDelegate? = nil {
    didSet {
        self.stripeView.delegate = stripeViewDelegate

    }

The error disappeared when I removed =nil from derived class.

VojtaStavik
  • 2,312
  • 1
  • 18
  • 30
1

I catch some exception today

class func createByAny(instance: Any?) -> ApiCollectionResponse { ... }

and this solved it:

class func createByAny(instance: Any) -> ApiCollectionResponse { ... }

Because "Any" type is any type event "nil", "AnyObject", optional, ... :) It is cannot be optional, it is already optional.

typealias Any = protocol<>
suquant
  • 2,085
  • 1
  • 12
  • 11
1

This error happens also if you accidentally declare a variable with a type matching its name:

    var sectionGroup: sectionGroup? { ... }
Saukwood
  • 301
  • 2
  • 3
  • Which would not have been an issue if you had followed Apple's naming convention and used a first upper case letter for the type. Which is likely why Apple has not stumbled over it. Further your answer looks to be the same as that of @aminhotob – qwerty_so Feb 23 '15 at 08:24
1

Ran into this error because of an extraneous generic type on an operator function, e.g.

func ==<T>(lhs: Foo, rhs: Foo) -> Bool {
  return lhs.bar == rhs.bar
}

In my case, removing <T> resolved the issue.

Sun
  • 777
  • 5
  • 13
  • Same problem here, in general it seems that defining generics that are not actually used will cause this error. – Kevin R Jun 06 '15 at 07:22
1

In my case I had declared a struct inside a func. Moving the struct to class level solved the issue.

Now that I write this I remember having had issues with struct inside funcs before. It was something else than the segmentation fault (which seems to become notorious with the Swift 1.2 beta). OMG Apple, what are you doing there?

qwerty_so
  • 35,448
  • 8
  • 62
  • 86
  • I had 3 variables in a struct and it worked fine, adding a 4th started causing the segmentation fault issue. changing struct to class solved it for me – Ehab Amer Mar 13 '16 at 16:45
1

Im my case, this happened when I did incorrect static initialization in a protocol. I found a way to get around, but a compiler should never produce a segmentation fault while building.

There are three files involved. A protocol NamedSegues.swift, a custom TableViewController that among other things implements the protocol which contains a callback, a custom TableViewCell that holds reference to this protocol to call the callback.

//file1
import Foundation
protocol NamedSegues {
    func  executeSegueWithId(id: String) -> Void
    static func getDefault() -> NamedSegues  // This was required because of init requirement in CustomCellView
}


//file2
class CustomController: UITableViewController, NamedSegues {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("CustomCellID", forIndexPath: indexPath ) as! CustomCellView

        // Configure the cell...
       //App logic...

        cell.parent = self
}

 //Mark: NamedSegues
     func executeSegueWithId(id: String) ->() {
        NSLog("Received callback to execute segue: \(id)")
        //
    }

    static func getDefault() -> NamedSegues { // I think this must be where it threw up.
        return self as! NamedSegues
    }

}


//file3

import UIKit

class CustomCellView: UITableViewCell {

    var id: String = "NoName"
    var parent: NamedSegues = NamedSegues.getDefault() // This is where it was needed.


override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        NSLog("Touched id: \(id)")


             parent.executeSegueWithId(id) // This is where parent was used.
     }
}

I got around it by using ?

In the protocol file, file1: delete the declaration of getDefault() In the CustomController file2: delete the implementation of getDefault. In the CustomCellView, file3:

    var parent: NamedSegues?
    ...
    parent?.executeSegueWithId(id)

The compiler should have caught this and given some error message instead of throwing a segmentation fault during build!

1

Seems like the Swift 2 compiler might not have been quite ready for prime-time! In case this helps anyone, I was getting a segmentation fault: 11 due to a mismatch with the variable type in a closure header, specifically in a Parse method, PFQuery.query.findObjectsInBackgroundWithBlock.

You can see the issue in more detail here: https://github.com/ParsePlatform/Parse-SDK-iOS-OSX/issues/280

Craig Grummitt
  • 2,945
  • 1
  • 22
  • 34
1

Like @Fjohn said, this was an issue related to unwrapping an optional for me (broke in both Xcode 7.0 beta 6 and Xcode 7). In my case, I was not unwrapping optional of the optional (what tipped me off was double ?? in the descriptor. Using if let solved the issue

double optional causing segmentation fault

mike.tihonchik
  • 6,855
  • 3
  • 32
  • 47
1

As others wrote above, for me this happened when I'm using an extension over a protocol but the signature of methods in the protocol don't match the implementations in an extension.

In my case, I had added a new parameter to the implementation (in the extension) but forgot to also add it to the method's signature in the protocol.

Alex
  • 919
  • 2
  • 7
  • 16
1

in my case, I tried to add a function parameter after a variadic parameter.

Reversing parameter sequence and making the variadic parameter the last parameter in the parameter list fixed it.

Gerd Castan
  • 6,275
  • 3
  • 44
  • 89
1

Swift 3.0 (Xcode 8.1) exhibits this issue when a protocol declares an optional variable, and an implementer implements that variable as a lazy initialised one.

Bug is reported here: https://bugs.swift.org/browse/SR-1825

Petter
  • 3,031
  • 1
  • 18
  • 12
1

Xcode 8.2.

Adding @nonobjc protocol implementation into extension causing segmentation faults. Move @nonobjc protocol implementation into class implementation.

Eugene P
  • 554
  • 4
  • 19
1

In my case the culprit was accidentally overloading a function expecting an array argument with one with a variadic argument:

public required init(_ args: Node...) {
}

When the superclass had it defined as an array:

public required init(_ args: [Node]) {
}
devios1
  • 36,899
  • 45
  • 162
  • 260
0

For me the following caused a segfault while type is an optional:

switch type {
    case .aType:
        // Do Something
    default:
        break
}

and this solved it:

switch type {
    case .Some(.aType):
        // Do Something
    default:
        break
}
blackjacx
  • 9,011
  • 7
  • 45
  • 56
0

I got this error with the following method signature in a custom UITableViewController.

func filterContentForSearchText(searchText: String)

changing to:

func filterContentForSearchText(searchText: String!)

fixed the problem.

elprl
  • 1,940
  • 25
  • 36
0

I had the same problem in an extension. My extension had two convenience initializers:

convenience init(context: NSManagedObjectContext) {
    let entityDescription = NSEntityDescription.entityForName("PropertyEntity", inManagedObjectContext: context)!
    self.init(entity: entityDescription, insertIntoManagedObjectContext: context)
}

convenience init(dictionary: NSDictionary, context: NSManagedObjectContext) {
    self.init(context: context)
    property1 = (dictionary["key"] as? String) ?? ""
    // More properties...
}

To get rid of the error I added an instance method map(dictionary: NSDictionary) and the segmentation fault error disappeared.

convenience init(dictionary: NSDictionary, context: NSManagedObjectContext) {
    self.init(context: context)
    map(dictionary)
}
Julian J. Tejera
  • 1,015
  • 10
  • 17
0

For me the issue was having my architectures not set to the standard. I had added i386 or something, just set it back to default xcodeproject arch and it compiled fine.

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
0

I had the same problem in a swift project. The issue was a function that should have returned an object, but didn't have a return in it. This sort of error used to be signaled while editing with Obj-C. It seems like t isn't the case in Swift.

Benjamin
  • 8,128
  • 3
  • 34
  • 45
0

It looks like it can be caused by a lot of reasons lol. In my case it was the pch file - when I tried to import the .pch file in bridging-header.h I got the segmentation fault and I assume maybe it's caused by the PROJECT-swift.h inside. So what I should do is putting everything swift needs into another const.h and #import "const.h" in both .pch and bridgng-header.h. This is a pretty dumb mistake I made but hope it can help some random guys come cross.

superarts.org
  • 7,009
  • 1
  • 58
  • 44
0

Discovered yet another way to get this error while attempting to use an empty struct with Argo:

Causes Segmentation Fault 11:

struct Action {
//  let foo: String
}

extension Action: Decodable {
  static func decode(json: JSON) -> Decoded<Action> {
    return .MissingKey("foo")
  }
}

Compiles just fine:

struct Action {
  let foo: String
}

extension Action: Decodable {
  static func decode(json: JSON) -> Decoded<Action> {
    return .MissingKey("foo")
  }
}

Sigh.

clozach
  • 5,118
  • 5
  • 41
  • 54
0

The problem for me was:

var startIndex : Int = etc...

Then I had:

startIndex++

Commenting out the startIndex++ prevented the error, so the fix was to use startIndex : Double and casting its comparison and such to Double

Matt H
  • 6,422
  • 2
  • 28
  • 32
0

I'll throw the reason I was getting this crash in the ring since so many different issues seem to be causing variations of this compiler issue.

My "while emitting SIL" was referencing an 'observeValueForKeyPath' method and I couldn't for the life of me figure out what was wrong with it (it worked fine in swift 1.2). The issue, oddly, ended up being with parenthesis around my case statements.

This worked before Swift 2.0...

switch (context) {
case(&myContext):
    print("observed")
}

This stopped the compiler error...

switch (context) {
case &myContext:
    print("observed")
}

Hope this answer helps a couple of people save a little time.

Steve E
  • 792
  • 10
  • 16
0

I also had same error, but it seemed to me that my Xcode has some issue while making build, after building several times the error was gone,but after I updated my Xcode to 7 the error was gone

Ajinkya Patil
  • 5,518
  • 4
  • 20
  • 22
0

Mine was due to conflict in overriding without optional return...

Base class :

func functionName(bla:String) -> UIView?

Derived class :

func functionName(bla:String) -> UIView

It was failing on the call, not the func declaration.

functionName("Help")
oshevans
  • 116
  • 1
  • 7
0

I ran across this today as well. In my case I implemented the protocol in a unit test file and forgot to implement one method that the default protocol implementation had left out.

LunaCodeGirl
  • 5,432
  • 6
  • 30
  • 36
0

For me trying to assign a get property which I unwrapped lines.last! was causing the issue. This code is invalid syntax, but the compiler would not pick up on it.

    var lines : [Line] = [Line()]

    var line : Line {
        get {
            return lines.last!
        } set {
            lines.last! = newValue
        }
    }
Sky
  • 86
  • 1
  • 2
0

I ran into this when I had a struct with 32 fields. I removed one field and everything was fine.

John Gibb
  • 10,603
  • 2
  • 37
  • 48
0

mine solved by removing this function in archive mode:

debugPrint(someObject)
mkhoshpour
  • 845
  • 1
  • 10
  • 22
0

I got the same error and wasted hours until I saw this blunder in my code:

let databaseRef: FIRDatabaseReference? = FIRDatabase.database().reference()

The problem was FIRDatabaseReference? Changed it to

let databaseRef: FIRDatabaseReference = FIRDatabase.database().reference()

and it started working like a charm! Hope this answer helps!

Anusha Kottiyal
  • 3,855
  • 3
  • 28
  • 45
Junaid Mukhtar
  • 815
  • 9
  • 16
0

In my case, the issue was, that I've had "Math.h" custom file and class in project, importing and using it caused an issue.

The strangest thing, that this file was in project during last 18 days, but everything worked fine. I guess, that it depends on how I'm using it, using it in Objective-C project, doesn't cause any issue.

So it is better to double check classes names.

nominanza
  • 201
  • 2
  • 6
0

got this error on Xcode 8 with Swift 3

I had to remove the throws keyword from this:

public extension FileManager {
    public func foo() throws -> URLRelationship {
        return URLRelationship.other
    }
}

to this:

public extension FileManager {
    public func foo() -> URLRelationship {
        return URLRelationship.other
    }
}
gietal
  • 129
  • 10
0

In my case, I had to change from this:

listItem.sortingOrder -= 1

to this:

listItem.sortingOrder = listItem.sortingOrder - 1

I found it by looking at the problematic function (pointed by the build error message While emitting SIL for 'myBadFunction'), and taking lines of code one by one until it worked, then focusing on the problematic line of code and trying different things. Good luck.

Nikolay Suvandzhiev
  • 8,465
  • 6
  • 41
  • 47
0

Yet another crash issue:

Variations of the following caused Xcode 8.2b2 compiler crashes in three places in my code:

return self.initialValue.mutableCopy() as AnyObject!

self.initialValue is defined as:

fileprivate  let initialValue:AnyObject!

I created various fixes for this, dependent on the context in my code. Here's one of the fixes:

let initialSetValue = self.initialValue as! NSMutableSet
let copy = NSMutableSet(set: initialSetValue);
return copy
Chris Prince
  • 7,288
  • 2
  • 48
  • 66
0

I solved it by removing the Build Settings configuration "Objective-C Bridging Header" string I've added manually.

Asaf Shveki
  • 736
  • 8
  • 11
0

I am working with xcode 7.3. Till after noon it was fine. suddenly I started seeing Seg Fault 11 for Objective C style selector. I don't know know what changed as xcode flipped on me (Of course I didn't update anything). It was literally just next run and it start freaking out. But I am able to get my project compile after adding #selector in one particular file for which xcode was complaining about.

Weird part is that It's not complaining about other files. It targeted only one file.

My recommendation see what file xcode is complaining about then work on all the warnings that its throwing for swift 3. You might be able to pass this seg fault.

Still at this moment reasons unknown. As I am able to clone the same project else where and compile just fine.

Alok C
  • 2,787
  • 3
  • 25
  • 44
0

Apple should fix this in Xcode to give a better experience to us all. I recommend you log a bug with apple here: https://bugreport.apple.com and reference bug: 32707221 so they see how many people its affecting.

For me it was unwrapping 2 objects out of order

eg:

if let passengers = car?.passengers, 
let car = car {
} 

instead of

if let car = car,
let passengers = car.passengers
 {
}

hard to find!

UKDataGeek
  • 6,338
  • 9
  • 46
  • 63
0

In my case the issue was in making extension with UITextFieldDelegate protocol to my class:

extension LoginPresenter: UITextFieldDelegate {}

To solve a problem I moved it to a class definition:

class LoginPresenter<T: LoginInteractionProtocol>: BasePresenter<T>, LoginPresenterProtocol, UITextFieldDelegate {
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Ned
  • 1,378
  • 16
  • 28
0

I was moving from Xcode 9 to 10.2. And here's a problem place

struct AbstractField<T>: ValidatableField {
    var name: String
    var value: Observable<Validated<T>>
    var setValue: (Validated<T>) -> Void
    var hint: Variable<String?>
    var error: Variable<AviaFieldError?>
    var isHidden: Binder<Bool>
    var isBeingEdited: Observable<Bool>
    var silentMode: Variable<Bool>
}

To solve a problem I replaced var to let for setValue closure.

struct AbstractField<T>: ValidatableField {
    var name: String
    var value: Observable<Validated<T>>
    let setValue: (Validated<T>) -> Void
    var hint: Variable<String?>
    var error: Variable<AviaFieldError?>
    var isHidden: Binder<Bool>
    var isBeingEdited: Observable<Bool>
    var silentMode: Variable<Bool>
}

Seems it was very hard to parse this construction for the compiler.

0

Just got this error because I was using a feature of Swift 5.1 in a target that was not setup for Swift 5.1. Specifically, I was using Self. to access a static function instead of ClassName. which works in Swift 5.1 but trying to use it in an older target caused this same error.

Helam
  • 1,385
  • 13
  • 17
0

I have had this error because my class does not conform to Equatable

Marwen Doukh
  • 1,946
  • 17
  • 26
0

Follow this process:

  1. Update pods of existing project
  2. Go to edit and select convert > current swift syntax
  3. In build setting enable bitcode to "NO"
  4. Add run the project
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

Segmentation faults can happen because of many reasons including compiler issues. I noticed in most cases using of protocols are involved and causes confusion in the compiler or sometimes module optimization process during compiler will lead to such an error.

I contacted Apple for one of these cases and they gave me a hidden attribute @_optimize(none) that you can add it to the initializer of your class to tell the compiler ignore the class from module optimization. I suggest give it a try if other methods suggested on the thread did not work for you.

@_optimize(none)
override init() {
    
    super.init()
}
Amir.n3t
  • 2,859
  • 3
  • 21
  • 28