57

Since Xcode 7 and Swift 2.0, I get the error above, like in the screenshot shown here:

screenshot of error log

I have no idea where this is coming from, cleaning and deleting derived data didn't work.

Anyone else experiencing this problem?

Project settings:

project settings

Target settings:

target settings

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
swalkner
  • 16,679
  • 31
  • 123
  • 210

37 Answers37

65

I faced this issue when used the same constant names in a guard construction

let activityVC = ...
        
guard let activityVC = activityVC else { return }

But xcode didn't show me any warning for this row.

22

This is normally a Swift compiler bug, and if compiler is already latest-version, we can only workaround it, for example:

Possible workarounds

#1

Go to project Build settings -> Swift Compiler - code generation -> Optimization Level -> For both Debug & Release select option "Fast,Single-File Optimization[-O]

settings

Above forces compiler to operate a little differently, which seems to prevent crash.

Note that both "-O" and "-Osize" may fix the crash, but I prefer -O to match release's settings, and avoid surprises in release.

#2

Go to "Build settings", and set "Compilation mode" to "Whole Module" instead of "Incremental".

By default for Debug it's Incremental, and for Release it's Whole Module.

#3

Try latest Swift compiler, which is named "toolchain" and is downloadable at:
https://swift.org/download

WARNING: You can not upload such "toolchain" build to App-store .

But at least you should be able to test locally.

For App-store, you need to compile with Swift compiler that comes with your Xcode (or latest Xcode, if your current Xcode version does not compile).

#4

Last and least (don't do this);
edit entire project's and/or pods' source-codes, and ensure guards have separate name than what they guard.
For example, replace:

guard let myVariableName = myVariableName else { return }

With something like:

guard let myDifferentName = myVariableName else { return }

Of course, now all lines after guard need to use myDifferentName.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
S_iOS
  • 229
  • 2
  • 3
  • 7
    This was happening to me on XCode 10.1. The optimization levels have changed to "No optimization", "Optimize for speed" or "Optimize for size", speed being the default for Release. I've changed that for size - it's something, at least - and it worked. – mgarciaisaia Nov 30 '18 at 19:59
  • For me the only thing that helped is turning off the optimization for Release. – Alex Apr 21 '20 at 13:13
  • Even if this works it would't be a good idea as it'll interfere with the debugger. – Stewart Thomson Jun 02 '20 at 14:43
7

I have the same problem with all Xcode 6.3 projects, I open in Xcode 7.0. I created a new project, copied all my source files and resources and everything worked without this compiler error. I thought this has something to do with the project settings. I turned off the Swift compile Optimization to "none" and the Trap 6 was gone away. Perhaps there are other settings, which also generate trouble, but for me this it was.

j.s.com
  • 1,422
  • 14
  • 24
  • I do have the optimization level in the Swift Compiler - Code Generation already set to None for Debug... I really would love to avoid the copying of all the resource files, hopefully Daniel gets some answers on the WWDC... – swalkner Jun 10 '15 at 16:50
  • There are two settings, one for the projects and one for the targets. Normally if you change the project, the target is also changed but not now. The problem is, that the "Fast [-O]" is slightly different written. So please go to either target and project and change the swift compiler both to none, if you already see "NONE", first select fast and then select "NONE" in the PopUp Menu. This is somewhat tricky. – j.s.com Jun 10 '15 at 18:08
  • I added images from my settings, I guess they are the way you mean, right? Doesn't work this way, unfortunately – swalkner Jun 10 '15 at 19:43
  • I am having the same issue as swalkner, and it's independent of any optimization settings, project or target. – promacuser Jun 10 '15 at 19:46
  • I have converted about 15 of my projects and all work. I set the LLVM 7.0 Compiler Settings to "Fastest [-O3]" and use Xcode Build 7A120f. The Swift Compiler Settings look a little bit different at my projects. There is no "Safety Checks" and no "AppStore" and not "AdHoc" but a "Release" which I set to Fast[-O], because it is not needed in Debug Mode. The Debug Setting is None [-Onone] as shown in your screenshot. Is it possible that you mail me a small project which shows the error, so I could test, if it runs here. I use Mac OS X 10.10.3 on a Retina Mac Book pro 15". Does a new project run? – j.s.com Jun 11 '15 at 13:57
  • I got the same error , but only shows on devices. if i choose an simulation, it runs well. I don't kown why... – Neko Nov 14 '17 at 03:40
  • @Neko Did you get solution for it ? – the monk Apr 04 '18 at 20:03
  • @ankit.tlp yes I have finally solved the problem . but I have forgot what I did at that time... – Neko Apr 09 '18 at 02:12
4

This worked for me, so just give it a try. i got this error while converting the code from swift 3 to swift 4.

Simply, go to Project>Target>Build Setting and search 'Swift Compiler - Code Generation' and set Optimization level to 'No Optimization[-Onone]'.

A. K.
  • 34,395
  • 15
  • 52
  • 89
2

In my case

Error

override func observeValueForKeyPath(keyPath: (String!)?, ofObject object: (AnyObject!)?, change: ([NSObject : AnyObject]!)?, context: UnsafeMutablePointer<Void>)

Ok

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>)
Luke
  • 11,426
  • 43
  • 60
  • 69
hunjuly
  • 21
  • 1
  • I had a similar issue and changing `override func touchesBegan(touches: Set, withEvent event: UIEvent!?)` to `override func touchesBegan(touches: Set, withEvent event: UIEvent?)` fixed the issue. I think the conversion to Swift 2 converted `UIEvent!` to `UIEvent!?`. – David L Jun 12 '15 at 02:46
  • 1
    I searched for the regular expression of ```!.?\?``` in my project and didn't find anything... But I guess it's going in the right direction, I just don't know what I have to search for... – swalkner Jun 12 '15 at 07:27
1

I got this error too on XCode 7 Beta 5. After I clean the build, then I got another error saying one of my class not conforming to the protocol I just changed. After I fix the issue, it builds. The protocol changes I made is to change two parameter type of a method from Int to Int32

Zhao
  • 904
  • 1
  • 11
  • 34
1

In my case,

The compiler would give me the message:

Incorrect number of arguments passed to called function!
%4 = call %swift.type* @_T015SimplifiedCoder6StructVMa() #1, !dbg !3112
<unknown>:0: error: fatal error encountered during compilation; please
file a bug report with your project and the crash log
<unknown>:0: note: Broken function found, compilation aborted!

but I realized that I missed a default generic parameter:

class Class<K> {
    init<T: Protocol>(_ value: T) where T.Key == K {}
}

protocol Protocol {
    associatedtype Key
    static func getClass<NewKey>(_: NewKey.Type) -> Class<NewKey>
}

struct Struct<K>: Protocol {

    typealias Key = K

    static func getClass<NewKey>(_: NewKey.Type) -> Class<NewKey> {
        let _self = Struct<NewKey>()
        return Class(_self)
    }
}

protocol CanGetClass {
    associatedtype StructType: Protocol
}

extension CanGetClass {
    func getClass<Key>(_: Key.Type) -> Class<Key> {
        return StructType.getClass(Key.self)
    }
}

struct R: CanGetClass {
    typealias StructType = Struct
}

changed:

typealias StructType = Struct

to:

typealias StructType = Struct<Int>

the extension of CanGetClass tried to call getClass on an incomplete type.

BMH500
  • 11
  • 2
1

I received this when did that:

protocol ProtocolA {
    associatedtype BType: ProtocolB
}

protocol ProtocolB {
    associatedtype AType: ProtocolA
}
1

Make sure you don't implement a private protocol into class extension. Most of the time would be quite strange to have a private protocol, but not necessary, depending on what you wish to encapsulate.

Something like, in the same file:

class C: ... {
}

extension C: P {
}

private protocol P: class {
}

Do this an you'll surely get Command failed due to signal: Abort trap: 6

Instead remove the private modifier from the protocol and the error is fixed.

Bogdan
  • 2,608
  • 2
  • 27
  • 26
1

I got this error when attempting to run tests. To solve it, I put this script into Terminal:

rm -rf ~/Library/Developer/Xcode/DerivedData

Deleting derived data resolved the issue

FullMetalFist
  • 208
  • 1
  • 2
  • 14
1

I was able to resolve it by making a change to the bridging header. In my case adding a line break was sufficient. Very strange bug.

ReDetection
  • 3,146
  • 2
  • 23
  • 40
1

I made mistake of using similar constant "name" in guard statement, causing this error.

guard let model = DataModel(JSON: response),
      let model = model.first else { return }

In above example, constant name "model" is used twice, use new constant name instead.

guard let parsedObj = DataModel(JSON: response),
      let model = parsedObj.first else { return }

NOTE: Xcode compiler do not warn you on this in compilation.

Please also check this answer which help to identify cause of this error. https://stackoverflow.com/a/67620285/5433935

nikdange_me
  • 2,949
  • 2
  • 16
  • 24
1

My code was crashing because of nested function. Example code is below :

Error :

extension UILabel {
    
    var attributedTextTruncates: Bool {
        
        guard numberOfLines > 0 else { return false }
        return countLabelLines() > numberOfLines
        
        func countLabelLines() -> Int {
            guard let myText = attributedText else {return 0}
            
            let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
            return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
        }
    }
}

Correct Code :

extension UILabel {
    
    var attributedTextTruncates: Bool {
        guard numberOfLines > 0 else { return false }
        return countLabelLines() > numberOfLines
    }
    
    private func countLabelLines() -> Int {
        guard let myText = attributedText else {return 0}
        let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
        return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
    }
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Rohit
  • 1,189
  • 12
  • 23
0

In my case, it was with setting a value to a parameter in a function to nil that was causing the error.

Before:

public func comparableValidator<T: Comparable>(minValue : T? = nil, maxValue : T? = nil, value: T) -> Void {
    if let min = minValue {
        _assertFunc(min <= value, "\(value) must be at least \(min)")
    }

    if let max = maxValue {
        _assertFunc(max >= value, "\(value) must be at most \(max)")
    }
}

After:

public func comparableValidator<T: Comparable>(minValue : T?, maxValue : T?, value: T) -> Void {
    if let min = minValue {
        _assertFunc(min <= value, "\(value) must be at least \(min)")
    }

    if let max = maxValue {
        _assertFunc(max >= value, "\(value) must be at most \(max)")
    }
}
0

I am able to reproduce this simply and consistently with a brand-new project created in Xcode 7.0 beta (7A120f). Note that the problem is likely more broad than the example, but this is 100% reproducible for me by only adding a single line to a new project. This problem also appears to exclusively apply to iOS, not OS X, at least for this example. Have submitted bug report # 21376523 to Apple.

  1. Create a brand-new project in Xcode 7.0 (7A120f). Type is "Game", Language is "Swift", Game Technology is "SceneKit".

  2. Build and run with default settings. Project builds and runs fine in simulator (you will see the default rotating 3D spaceship model).

  3. Add a single SCNVector3 property to GameViewController.swift, like this:

    class GameViewController: UIViewController {  
      var p = SCNVector3Zero  
    

--> Produces "Abort trap: 6". Project will no longer compile.

  1. Change the constant to an empty initializer.

    class GameViewController: UIViewController {  
      var p = SCNVector3()  
    

--> Same problem, "Abort trap: 6"

  1. Remove property, restoring to the clean project state.

--> "Abort trap: 6" is gone, project again compiles and runs.

  1. Change "var" to "let".

    class GameViewController: UIViewController {  
      let p = SCNVector3Zero
    

-- > Compiles and runs.

  1. Change property type to SCNVector4 instead of SCNVector3.

    class GameViewController: UIViewController {  
      var p = SCNVector4Zero
    

-- > Compiles and runs.

EDIT: This problem is fixed in Xcode 7.0 beta-2 (7A121l), if you are getting "Abort trap: 6" due to using a float 3 vector type (such as SCNVector3). From the release notes:

• A compiler crash when calling C or Objective-C functions that take SIMD float3 parameters has been fixed. (21294916)

Ben Stahl
  • 1,139
  • 11
  • 11
0

Ok, in my case it was because I had an enum nested in a generic class. Now, the strange thing, is that when I isolated the problem (into the BaseDao2), the compiler told me the right error, but in my real BaseDao implementation (which has more stuff), it throw "trap 6".

Type 'DaoError2' nested in generic type 'BaseDao2' is not allowed

When I had this:

class BaseDao2<T>: InjectRestSession{

    enum DaoError2: ErrorType{
        case FAILED_RESPONSE(String)
        case INVALID_RESULT(String)
        case FAIL_TO_LIST, FAIL_TO_GET
    }

    func get() -> T?{
        return nil
    }
}

Anyway, in my case, I move the DaoError out of the BaseDao and everything compiled. Anyway, my feeling is that "trap 6" is what something cannot compile and the compiler got confused. Starting from a simple case, and adding back what you think might be causing the problem can be helpul to identify the problem by getting the right compile error. In other word, you have to be gentle with the swift compiler.

Jeremy Chone
  • 3,079
  • 1
  • 27
  • 28
0

This is what caused the error for me.

Before:

    for (key,value) in hash{
        count += value.count
    }

After:

    for (_,value) in hash{
        count += value.count
    }

It didn't like it that key was never being used anywhere. I am not sure why it should cause the build to fail though.

boidkan
  • 4,691
  • 5
  • 29
  • 43
0

I managed to get my project to build by setting the optimisation level to 'None' under the 'Swift Compiler - Code Generation' menu in the target (not the project) settings. See the screenshot below...

enter image description here

This shouldn't be a permanent solution because it more than doubles the size of the ipa. It should be possible to switch optimisation back on when Xcode 7 comes out of beta.

PJeremyMalouf
  • 613
  • 6
  • 15
0

In my case i had @objc protocol with optional methods and when i called its methods also in swift class i got that error, after removing the optional keyword from functions in the protocol the error was gone.

before (with error):

@objc protocol SomeDelegate:NSObjectProtocol{

    optional func someDelegateMethod()
}

class MySwiftClass{
    func notifyMyDelegate(){
        mydelegate?.someDelegateMethod?() //this line caused the error
    }
}

after:

@objc protocol SomeDelegate:NSObjectProtocol{

    func someDelegateMethod()
}

class MySwiftClass{
    func notifyMyDelegate(){
        mydelegate?.someDelegateMethod()
    }
}
Oleg Sherman
  • 2,772
  • 1
  • 21
  • 20
0

for me.. I modified the content of a @objc function like so:

before:

        @objc func didConnectWithSession() {
           context!.stream.disconnectAfterSending()
        }

after:

        @objc func didConnectWithSession() {
           //context!.stream.disconnectAfterSending()
        }

This caused the error. I resolved by removing the entire function.

deLux_247
  • 161
  • 1
  • 5
0

I got this message when using do-try-catch in a Failable initializer:

public init?() {
    do {
        ...
        super.init(superParam: try getParamForSuper())
        ...
    } catch {
        ...
    }
}

The compilation succeeded when moving the try call to it's own local variable:

public init?() {
    do {
        ...
        let superParam = try getParamForSuper()
        super.init(superParam: superParam)
        ...
    } catch {
        ...
    }
}
Joakim
  • 3,224
  • 3
  • 29
  • 53
0

In my case I had a private struct Constants declared in both class A and extension A.

Probably it should be giving an error but it didn't.

Tung Fam
  • 7,899
  • 4
  • 56
  • 63
0

To me what caused this error was:

I created a file to create extensions on UIView. Inside this file, I created a private protocol named Foo.

Then I made:

extension UIView: Foo

Removing the private from the protocol made the error go away.

I guess this is probably a bug. The compiler should warn us about the issue. The same way it warns us we can't add private conformances to types it should tell us that conformance should be using a "public/internal" protocol.

Nuno Gonçalves
  • 6,202
  • 7
  • 46
  • 66
0

I resolved this problem with these steps:

  1. ran 'pod deintegrate'

  2. Makesure podfile like this: platform :ios, '8.0' use_frameworks!

  3. ran 'pod install'

cmaher
  • 5,100
  • 1
  • 22
  • 34
QL M
  • 9
  • 1
0

In my case, renames several parameters of init methods which is a protocol fails the compilation. I solve it by do it one by one, compiles again after each change.

Bill Chan
  • 3,199
  • 36
  • 32
0

I was having this same problem and I found the problem was that I had changed the build system to "New Build System" after reading an article on "how to speed up your builds" (This is the article btw here)

So to go back to the standard build system:

  1. To enable the new build system, go to File → Project Settings (or Workspace Settings).
  2. Change Build System to Standard Build System.

enter image description here

Hope it helps someone and don't waste hours trying to find out why this was not working!

Andres
  • 11,439
  • 12
  • 48
  • 87
0

I didn't try other solutions. I got this problem for this setup:

func speacialAdd(_ num1: Int, to num2: Int){
    func specialMultiply(_ digit1: Int, with digit2: Int = num2){ // SOURCE OF PROBLEM
        print(digit2)
        print(digit1)
    }

    specialMultiply(5)
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print(speacialAdd(5, to: 6))
    }
}

This line is the source of problem. Defaulting it to a argument seems to not work for a nested function

func specialMultiply(_ digit1: Int, with digit2: Int = num2) // ERROR

Solutions are:

func specialMultiply(_ digit1: Int, with digit2: Int) // OK
func specialMultiply(_ digit1: Int, with digit2: Int = 6) // OK

FWIW I actually first wrote this in playground and got a different error:

Playground execution failed:

error: Couldn't lookup symbols:
__T013__lldb_expr_111speacialAddySi_Si2totF4num2L_Sifau

mfaani
  • 33,269
  • 19
  • 164
  • 293
0

In Xcode 9.3, I have re-installed the specific pod, in which warnings appeared and cleared derived data again n again. It worked for me :)

0

I fixed it by going to Xcode -> Preferences -> Locations -> Set Relative option to Derived Data.

Setting Derived Data

jawad
  • 775
  • 6
  • 16
0

For me it was MD5.swift issue

What you have to do is search in your project for file name "MD5.swift" even in the pods

and replace all the content with this file here

https://github.com/onmyway133/SwiftHash/blob/master/Sources/MD5.swift

Ahmed Safadi
  • 4,402
  • 37
  • 33
0

This issue is still present in Xcode 10.2.1. After cleaning the build folder, the error went away.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
0

For me below statement cause an error.

let dict = mainDict as [String:String]

Fix the issue by force unwraps

let dict = mainDict as! [String:String]

There is nothing related to the compiler. It is just type casting issue, Apple should give proper description instead of the giving compiler error

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
0

My case, Swift 5.1, Xcode 10.3 (10G8)

Code was crashing Swift when a nested function was using the argument of an outer function as a default parameter.

e.g.

func foo(duration: TimeInterval) {
    func bar(duration: TimeInterval = duration) {
    }
}

I hope this helps.

Womble
  • 4,607
  • 2
  • 31
  • 45
0

In my case search for

[String: String]

replace with

[String: Any]
Marosdee Uma
  • 719
  • 10
  • 14
0

In my case the problem with "Abort trap: 6" was caused by setting a value of a @Published property defined in a super class, that inherits from ObservableObject (Swift 5).

Error:

class MySuperClass : ObservableObject {
   @Published var myProperty : Int = 0
}

class MySubClass : MySuperClass {
   func someFunc() {
     myProperty = 1
   }
}

Ok:

class MySuperClass : ObservableObject {
   @Published var myProperty : Int = 0

   func setMyProperty(value: Int) {
      myProperty = value
   }
}

class MySubClass : MySuperClass {
   func someFunc() {
     setMyProperty(value: 1) 
   }
}
0

in Xcode 11 and swift 5: Go to project Build settings -> Swift Compiler - code generation -> Optimization Level -> For both Debug & Release select option "No Optimaiztion[-Onone]

enter image description here

BatyrCan
  • 6,773
  • 2
  • 14
  • 23
-1

My problem was with the line:

return ()

i removed the line and problem fixed!

Mehrdad
  • 1,050
  • 1
  • 16
  • 27