Segmentation fault 11 when passing a capture block to a DispatchQueue - ios

I am getting a Segmentation fault on both Swift 4 and Swift 4.2 on a capture block for a DispatchQueue.
I am trying to provide a capture block to the escaping parameter of a DispatchQueue to guarantee that the object passed to the called closure is alive when it will be called.
The code looks something like this:
import Foundation
struct Response {
let outcome: String?
}
enum NotEvenError: Error {
case notEven
}
struct IsEvenService {
typealias SuccessCallback = (Response) -> Void
typealias FailureCallback = (Error?) -> Void
func perform(success: #escaping SuccessCallback, failure: #escaping FailureCallback) {
let number = Int.random(in: 0 ... 10)
if number%2 == 0 {
let outcome = Response(outcome: "it is")
success(outcome)
} else {
failure(NotEvenError.notEven)
}
}
}
func runTest(success: #escaping (Response) -> Void, failure: #escaping (Error?) -> Void) {
let service = IsEvenService()
service.perform(success: { (response) in
if response.outcome != nil {
DispatchQueue.main.async { [resp = response] in
success(resp)
}
}
},
failure: { (error) in
DispatchQueue.main.async { [err = error] in
failure(err)
}
})
}
The problematic part is the following:
DispatchQueue.main.async { [err = error] in
failure(err)
}
This is a sample file that can be easily verified with a swiftc call in the command line.
Here is the outcome:
Apple Swift version 4.2 (swiftlang-1000.11.37.1 clang-1000.11.45.1)
Target: x86_64-apple-darwin17.7.0
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c -primary-file test.swift -target x86_64-apple-darwin17.7.0 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -color-diagnostics -module-name test -o /var/folders/fn/wh62twgj54180b7x1dx9j6080000gp/T/test-d0f7f4.o
0 swift 0x000000010720964a PrintStackTraceSignalHandler(void*) + 42
1 swift 0x0000000107208dfe SignalHandler(int) + 302
2 libsystem_platform.dylib 0x00007fff7ac3ff5a _sigtramp + 26
3 libsystem_platform.dylib 0x00007ffeec7e0000 _sigtramp + 1908015296
4 swift 0x0000000103eef293 swift::ASTVisitor<(anonymous namespace)::StmtEmitter, void, void, void, void, void, void>::visit(swift::Stmt*) + 6531
5 swift 0x0000000103ea826e swift::Lowering::SILGenFunction::emitFunction(swift::FuncDecl*) + 462
6 swift 0x0000000103e0be14 swift::Lowering::SILGenModule::emitFunction(swift::FuncDecl*)::$_1::operator()(swift::SILFunction*) const + 516
7 swift 0x0000000103e0b142 swift::Lowering::SILGenModule::emitFunction(swift::FuncDecl*) + 1042
8 swift 0x0000000103e1501b swift::Lowering::SILGenModule::emitSourceFile(swift::SourceFile*, unsigned int) + 939
9 swift 0x0000000103e16bd5 swift::SILModule::constructSIL(swift::ModuleDecl*, swift::SILOptions&, swift::FileUnit*, llvm::Optional<unsigned int>, bool) + 1333
10 swift 0x00000001034983fe performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 28990
11 swift 0x000000010348ddc5 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 7717
12 swift 0x0000000103433a35 main + 1349
13 libdyld.dylib 0x00007fff7a931015 start + 1
14 libdyld.dylib 0x000000000000000f start + 2238509051
Stack dump:
0. Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c -primary-file test.swift -target x86_64-apple-darwin17.7.0 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -color-diagnostics -module-name test -o /var/folders/fn/wh62twgj54180b7x1dx9j6080000gp/T/test-d0f7f4.o
1. While emitting SIL for 'runTest(success:failure:)' at test.swift:26:1
2. While silgen emitFunction SIL function "#$S4test7runTest7success7failureyyAA8ResponseVc_ys5Error_pSgctF".
for 'runTest(success:failure:)' at test.swift:26:1
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: compile command failed due to signal 11 (use -v to see invocation)
Is it safe to assume that if I do not pass a capture block that the object will be retained when the closure is executed?
If I do the following, it compiles:
let uselessTempError = error
DispatchQueue.main.async { [err = uselessTempError] in
failure(err)
}

You don't need the [err = error] part. The following block will keep a strong reference to error:
DispatchQueue.main.async {
failure(error)
}

Related

com.apple.main-threadEXC_BREAKPOINT, Crash registered on Fabric on Fetching User Facebook Profile in iOS

There is a crash registered on Fabric in my app when I am fetching user's facebook profile information. It is only crashing on release build. I am not able to reproduce the crash even after trying it multiple times. I am fetching the profile in a separate network manager class. I have implemented it using closure and callbacks.
Below is the stack trace and crash report from Fabric.
# OS Version: 11.4.1 (15G77)
# Device: iPhone 6s
# RAM Free: 6%
# Disk Free: 14.3%
#0. Crashed: com.apple.main-thread
0 Roamer 0x104b364a4 LoginViewController.(fetchUserProfile() -> ()).(closure #1) (LoginViewController.swift:250)
1 Roamer 0x104b36d84 partial apply for LoginViewController.(fetchUserProfile() -> ()).(closure #1) (LoginViewController.swift)
2 Roamer 0x104b7ed4c specialized NetworkManager.(fetchFBProfile(((display : Int, status : String, message : String), FBProfileResponse) -> ()) -> ()).(closure #1) (NetworkManager.swift:1234)
3 Roamer 0x104b7e7a4 partial apply for NetworkManager.(fetchFBProfile(((display : Int, status : String, message : String), FBProfileResponse) -> ()) -> ()).(closure #1) (NetworkManager.swift)
4 Roamer 0x104b7e7ec HTTPURLResponse?GraphRequestResult<MyProfileRequest> (NetworkManager.swift)
5 FacebookCore 0x1058dc550 HTTPURLResponse?GraphRequestResult<A> (GraphRequestConnection.swift)
6 FacebookCore 0x1058daaac (HTTPURLResponse?, GraphRequestResult<A>)() (GraphRequestConnection.swift)
7 FacebookCore 0x1058dc8d8 static GraphRequestConnection.sdkRequestCompletion<A where ...> (from : (HTTPURLResponse?, GraphRequestResult<A>) -> ()) -> (FBSDKGraphRequestConnection?, Any?, Error?) -> () empty-list Error first-element-marker HTTPURLResponse (GraphRequestConnection.swift:152)
8 FacebookCore 0x1058dac18 static GraphRequestConnection.sdkRequestCompletion<A where ...> (from : (HTTPURLResponse?, GraphRequestResult<A>) -> ()) -> (FBSDKGraphRequestConnection?, Any?, Error?) -> () empty-list Error first-element-marker HTTPURLResponse (GraphRequestConnection.swift)
9 FacebookCore 0x1058dc5f8 FBSDKGraphRequestConnection?Any?Error? (GraphRequestConnection.swift)
10 FacebookCore 0x1058dc4bc (FBSDKGraphRequestConnection?, Any?, Error?)() (GraphRequestConnection.swift)
11 FacebookCore 0x1058c58bc FBSDKGraphRequestConnection?Any?Error? (AccessToken.swift)
12 FBSDKCoreKit 0x1056a43fc -[FBSDKGraphRequestMetadata invokeCompletionHandlerForConnection:withResults:error:] (FBSDKGraphRequestMetadata.m:48)
13 FBSDKCoreKit 0x1056a1d2c __82-[FBSDKGraphRequestConnection processResultBody:error:metadata:canNotifyDelegate:]_block_invoke (FBSDKGraphRequestConnection.m:754)
14 FBSDKCoreKit 0x1056a1b88 -[FBSDKGraphRequestConnection processResultBody:error:metadata:canNotifyDelegate:] (FBSDKGraphRequestConnection.m:818)
15 FBSDKCoreKit 0x1056a163c __64-[FBSDKGraphRequestConnection completeWithResults:networkError:]_block_invoke (FBSDKGraphRequestConnection.m:738)
16 CoreFoundation 0x1825a0a20 -[__NSArrayM enumerateObjectsWithOptions:usingBlock:] + 216
17 FBSDKCoreKit 0x1056a13e0 -[FBSDKGraphRequestConnection completeWithResults:networkError:] (FBSDKGraphRequestConnection.m:717)
18 FBSDKCoreKit 0x1056a087c -[FBSDKGraphRequestConnection completeFBSDKURLSessionWithResponse:data:networkError:] (FBSDKGraphRequestConnection.m:582)
19 FBSDKCoreKit 0x10569ea54 __36-[FBSDKGraphRequestConnection start]_block_invoke_2 (FBSDKGraphRequestConnection.m:222)
20 libdispatch.dylib 0x181fb8aa0 _dispatch_call_block_and_release + 24
21 libdispatch.dylib 0x181fb8a60 _dispatch_client_callout + 16
22 libdispatch.dylib 0x181fc565c _dispatch_main_queue_callback_4CF$VARIANT$mp + 1012
23 CoreFoundation 0x18266f070 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
24 CoreFoundation 0x18266cbc8 __CFRunLoopRun + 2272
25 CoreFoundation 0x18258cda8 CFRunLoopRunSpecific + 552
26 GraphicsServices 0x184572020 GSEventRunModal + 100
27 UIKit 0x18c5ac758 UIApplicationMain + 236
28 Roamer 0x104b1fbf8 main (DetailsCell.swift:28)
29 libdyld.dylib 0x18201dfc0 start + 4
--
Below is the function in LoginViewController from where I am calling the fetchFBProfile function in NetworkManager:
func fetchUserProfile()
{
NetworkManager.sharedInstance.fetchFBProfile() { [unowned self] (responseStatus: ResponseStatus, responseObj: FBProfileResponse) in
if responseStatus.status == "Success"
{
self.fbSignIn(responseObj)
}
else{
if responseStatus.display == 1
{
self.showBanner(Strings.failureHeaderMsg, responseStatus.message, true, true)
}
else{
self.showBanner(Strings.failureHeaderMsg, Strings.serverErrorMsg, true, true)
}
}
}
}
Below is the fetchFBProfile function in NetworkManager:
func fetchFBProfile( _ completion: #escaping GenericResponseWithObj<FBProfileResponse>) -> Void {
let connection = GraphRequestConnection()
progress.show(style: ProgressStyle())
connection.add(MyProfileRequest()) { response, result in
switch result {
case .success(let response):
let fBProfileResponse = FBProfileResponse()
fBProfileResponse.birthday = response.birthday
fBProfileResponse.email = response.email
fBProfileResponse.gender = response.gender
fBProfileResponse.id = response.id
fBProfileResponse.locale = response.locale
fBProfileResponse.name = response.name
fBProfileResponse.profilePictureUrl = response.profilePictureUrl
completion((0, "Success", "Facebook SignIn Successful"), fBProfileResponse)
case .failed(let error):
print("Custom Graph Request Failed: \(error)")
self.progress.dismiss()
completion((0, "Failure", "Couldn't fetch user response"), FBProfileResponse())
}
}
connection.start()
}
I can't understand the crash report from fabric and also the app is working flawlessly on my end. Any help would be deeply appreciated. Thanks

Why does swift not compile when referring to protocol method directly? [duplicate]

This question already has an answer here:
Storing/passing Function Types from swift protocols
(1 answer)
Closed 5 years ago.
Given the following struct:
struct TestStruct {
func test() {
print("Something")
}
}
Referencing the test function like this works:
let testFunc = TestStruct.test // (TestStruct) -> () -> Void
In order to execute the function you would have to do the following:
testFunc(TestStruct())() // Prints "Something"
Say you make TestStruct conform to a protocol:
protocol Test {
func test()
}
extension TestStruct: Test {}
Now trying to rather reference the test function through the protocol like this does not work:
let testFunc = Test.func // Does not compile, no error message
Shouldn't the type of testFunc be (Test) -> () -> Void? And why is it now compiling?
The code you wrote is intended to work at some point, according to SR-75. They haven't implemented it yet.
The fact that the compiler crashes instead of printing an error means that you have found a compiler bug.
:; xcrun swift
Welcome to Apple Swift version 4.0 (swiftlang-900.0.54.10 clang-900.0.31). Type :help for assistance.
1> struct TestStruct {
2. func test() {
3. print("Something")
4. }
5. }
6> protocol Test {
7. func test()
8. }
9.
10. extension TestStruct: Test {}
11> let testFunc = Test.test
Segmentation fault: 11
“Segmentation fault: 11” means the compiler crashed. You should go to https://bugs.swift.org/, create an account if you don't have one, and file a bug report.
You can see the compiler stack trace by putting the test code in a file and compiling it:
:; echo 'protocol Test { func test() }; let testFunc = Test.test' > main.swift && xcrun swiftc main.swift
0 swift 0x000000010b5efeaa PrintStackTraceSignalHandler(void*) + 42
1 swift 0x000000010b5ef2e6 SignalHandler(int) + 662
2 libsystem_platform.dylib 0x00007fff9742fb3a _sigtramp + 26
3 libsystem_platform.dylib 0x00007f82e307de00 _sigtramp + 1271194336
4 swift 0x0000000108818c2c swift::Lowering::SILGenFunction::manageOpaqueValue(swift::Lowering::SILGenFunction::OpaqueValueState&, swift::SILLocation, swift::Lowering::SGFContext) + 188
5 swift 0x000000010882fa1b swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 11067
6 swift 0x000000010882d6a1 swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 1985
7 swift 0x0000000108838f01 swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 49185
8 swift 0x0000000108849329 void llvm::function_ref<void (swift::Expr*)>::callback_fn<swift::Lowering::RValue swift::Lowering::SILGenFunction::emitOpenExistentialExpr<swift::Lowering::RValue, (anonymous namespace)::RValueEmitter::visitOpenExistentialExpr(swift::OpenExistentialExpr*, swift::Lowering::SGFContext)::$_5>(swift::OpenExistentialExpr*, (anonymous namespace)::RValueEmitter::visitOpenExistentialExpr(swift::OpenExistentialExpr*, swift::Lowering::SGFContext)::$_5)::'lambda'(swift::Expr*)>(long, swift::Expr*) + 41
9 swift 0x00000001088499e7 swift::Lowering::SILGenFunction::emitOpenExistentialExprImpl(swift::OpenExistentialExpr*, llvm::function_ref<void (swift::Expr*)>) + 1591
10 swift 0x000000010882e1cb swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 4843
11 swift 0x000000010882cb74 swift::Lowering::SILGenFunction::emitExprInto(swift::Expr*, swift::Lowering::Initialization*) + 148
12 swift 0x000000010881ccf6 swift::Lowering::SILGenFunction::emitPatternBinding(swift::PatternBindingDecl*, unsigned int) + 198
13 swift 0x00000001087ce3cf swift::ASTVisitor<swift::Lowering::SILGenModule, void, void, void, void, void, void>::visit(swift::Decl*) + 559
14 swift 0x00000001087cd4ab swift::Lowering::SILGenModule::emitSourceFile(swift::SourceFile*, unsigned int) + 1115
15 swift 0x00000001087cee39 swift::SILModule::constructSIL(swift::ModuleDecl*, swift::SILOptions&, swift::FileUnit*, llvm::Optional<unsigned int>, bool) + 841
16 swift 0x0000000107f6dedc performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 13020
17 swift 0x0000000107f69394 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 7332
18 swift 0x0000000107f1ead8 main + 12248
19 libdyld.dylib 0x00007fff97220235 start + 1
20 libdyld.dylib 0x000000000000000f start + 1759378907
Stack dump:
0. Program arguments: /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c -primary-file main.swift -target x86_64-apple-macosx10.9 -enable-objc-interop -sdk /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -color-diagnostics -module-name main -o /var/folders/kn/1d839myx4tlghz34f_lh3hvc0000gn/T/main-65ce73.o
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: compile command failed due to signal 11 (use -v to see invocation)
The difference between your struct and your protocol is that the protocol does not implement a method test. It just declares a method named test. The expression TestStruct.test returns a reference to the implementation of the method test of the struct. Because the protocol has no implementation for test, the compiler can't return a reference to this.
Note: The protocol Test does not know anything about its implementing classes or structs. Thus, Test.test cannot return the reference to TestStruct.test. In the case of multiple implementations of Test this would be ambigious, too.
Conclusion: You can't refer to method's implementation of protocols, because they have no implementation.

Workaround for specific generic type parameter

The situation:
I have two protocols, one with a static method:
protocol DataSourceable {
static func getMoreData<T: DataAccepting>(someObject: T)
}
protocol DataAccepting {
func accept(data: [Any])
}
extension DataAccepting where Self: UIViewController { }
which compiles fine.
Once I define a class with a type parameter conforming to DataSourceable:
class SampleViewController<T: DataSourceable>: UIViewController {...}
I get a Segmentation Fault: 11 and the compiler crashes.
0 swift 0x0000000112445b6d PrintStackTraceSignalHandler(void*) + 45
1 swift 0x00000001124455b6 SignalHandler(int) + 470
2 libsystem_platform.dylib 0x00007fffa4bd9bba _sigtramp + 26
3 libsystem_platform.dylib 0x0000000000000002 _sigtramp + 1531077730
4 swift 0x000000010f8bd5bd swift::irgen::emitCategoryData(swift::irgen::IRGenModule&, swift::ExtensionDecl*) + 2285
5 swift 0x000000010f8c2425 swift::irgen::IRGenModule::emitGlobalDecl(swift::Decl*) + 1189
6 swift 0x000000010f8c1e85 swift::irgen::IRGenModule::emitSourceFile(swift::SourceFile&, unsigned int) + 133
7 swift 0x000000010f98dfe2 performIRGeneration(swift::IRGenOptions&, swift::ModuleDecl*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1282
8 swift 0x000000010f85c1c7 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*) + 23687
9 swift 0x000000010f854265 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 17029
10 swift 0x000000010f81182d main + 8685
11 libdyld.dylib 0x00007fffa49cd255 start + 1
12 libdyld.dylib 0x00000000000000c6 start + 1533226610
**More_Stuff**...
While emitting IR for source file /xx/xx/xx/xx/xx/xx/xx/SampleViewController.swift
The end goal is to be able to do this:
class SampleViewController<T: DataSourceable>: UIViewController, DataAccepting {
var intArray = [Int]()
func setup() {
T.getMoreData(dataAcceptor: self)
}
func accept(data: [Any]) {
intArray = data
}
}
struct SampleModel: DataSourceable {
static func getMoreData<T: DataAccepting>(dataAcceptor: T) {
var anIntArray = [Int]()
someObject.accept(anIntArray)
}
}
And then make a SampleViewController<SampleModel>.
This will allow me to let the SampleModel deal with sourcing data for the controller. The SampleModel decides how to get the data, then using the accept() function on the controller it can give the data to the SampleController.
This seems to be a compiler bug. However, you should avoid this design in general, as we discussed in chat.

Swift compiler segmentation fault after Swift 3 / Xcode 8 port

I have checked multiple answers here in SO, but no solution seems to work for me. When compiling my iOS (≥9.3) app, the following compiler error appears since I converted my project to Swift 3 / Xcode 8.
I tried to clean, delete DerivedData, rebuild Carthage frameworks, etc. - but nothing worked - yet.
Maybe somebody who has experienced this before can immediately spot the problem.
Console output / Stacktrace :
0 swift 0x000000010bc8cb6d PrintStackTraceSignalHandler(void*) + 45
1 swift 0x000000010bc8c5b6 SignalHandler(int) + 470
2 libsystem_platform.dylib 0x00007fffd300dbba _sigtramp + 26
3 libsystem_platform.dylib 000000000000000000 _sigtramp + 754918496
4 swift 0x00000001090c98d2 llvm::Value* llvm::function_ref<llvm::Value* (unsigned int)>::callback_fn<swift::irgen::emitArchetypeWitnessTableRef(swift::irgen::IRGenFunction&, swift::CanTypeWrapper<swift::ArchetypeType>, swift::ProtocolDecl*)::$_0>(long, unsigned int) + 530
5 swift 0x00000001091a7600 swift::irgen::emitImpliedWitnessTableRef(swift::irgen::IRGenFunction&, llvm::ArrayRef<swift::irgen::ProtocolEntry>, swift::ProtocolDecl*, llvm::function_ref<llvm::Value* (unsigned int)> const&) + 240
6 swift 0x00000001090c96a7 swift::irgen::emitArchetypeWitnessTableRef(swift::irgen::IRGenFunction&, swift::CanTypeWrapper<swift::ArchetypeType>, swift::ProtocolDecl*) + 247
7 swift 0x00000001091a39cd swift::SILWitnessVisitor<(anonymous namespace)::WitnessTableBuilder>::visitProtocolDecl(swift::ProtocolDecl*) + 5997
8 swift 0x00000001091a14d7 swift::irgen::IRGenModule::emitSILWitnessTable(swift::SILWitnessTable*) + 503
9 swift 0x00000001091138ed swift::irgen::IRGenerator::emitGlobalTopLevel() + 2077
10 swift 0x00000001091d4fcb performIRGeneration(swift::IRGenOptions&, swift::ModuleDecl*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1259
11 swift 0x00000001090a31c7 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*) + 23687
12 swift 0x000000010909b265 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 17029
13 swift 0x000000010905882d main + 8685
14 libdyld.dylib 0x00007fffd2e01255 start + 1
15 libdyld.dylib 0x0000000000000067 start + 757067283
And the problematic file / class is the following:
class JSONDataProvider<Input, Output, APIInformation>: DataProvider
where APIInformation: APIAccessInformation, APIInformation.Input == Input,
Output: JSONDataType, Input: Equatable, Input: SignificanceComparable
{
static var updateCallbacksWithoutInputChange: Bool { return false }
// MARK: - Protocol Variables
var callbackId: Int = 0
var callbacks: [Int : (Result<(Output, Input)>) -> ()]
var inputCache: Input?
var outputCache: Result<(Output, Input)>?
// MARK: - Private Properties
fileprivate let apiInformation: APIInformation
fileprivate let requestHandler: URLRequestHandler
// MARK: - Init
init(apiInformation: APIInformation, requestHandler: URLRequestHandler)
{
self.apiInformation = apiInformation
self.requestHandler = requestHandler
self.callbacks = [:]
}
}
For context: (leaving out extensions)
protocol DataProvider
{
associatedtype Input: Equatable, SignificanceComparable
associatedtype Output
static var updateCallbacksWithoutInputChange: Bool { get }
var inputCache: Input? { get set }
var outputCache: Result<(Output, Input)>? { get set }
var callbackId: Int { get set }
var callbacks: [Int : (Result<(Output, Input)>) -> Void] { get set }
func fetchData(from input: Input)
mutating func registerCallback(_ callback: #escaping (Result<(Output, Input)>) -> Void) -> Int
mutating func unregisterCallback(with id: Int)
}
And:
protocol APIAccessInformation
{
associatedtype Input: Equatable, SignificanceComparable
var requestMethod: Alamofire.HTTPMethod { get }
var baseURL: String { get }
func apiParameters(for input: Input) -> [String : Any]
}
Any ideas? Thank you!
Turns out the generic type was the problem. As nobody seems to know exactly why, I have adapted my architecture so I don't need this generic type.
I'm leaving this question here in case others run into a similar issue or someone who knows the exact reason and fix finds this thread.

MKMapViewDelegate Command failed due to signal: Segmentation fault: 11

i have a very weird problem with a MKMapViewDelegate when i implement this method give me an error that i do not understand
The error only disappear when i delete the whole function,
i tried to make a empty function returning nil but give me the same error.
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation.isKindOfClass(MKUserLocation.classForCoder()) {
return nil
}
let AnnotationIdentifier:NSString = "AnnotationIdentifier"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(AnnotationIdentifier)
if annotationView != nil {
return annotationView
}else {
var annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: AnnotationIdentifier)
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "btn_fav.png")
return annotationView
}
}
The error:
Command failed due to signal: Segmentation fault: 11
CompileSwift normal arm64 /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Vistas/Proyecto/MapaViewController.swift
cd /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c "/Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Classes/NetClass/Downloader.swift" -primary-file "/Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Vistas/Proyecto/MapaViewController.swift" "/Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Vistas/Widget/ToggleView.swift" .
.
.
.
0 swift 0x00000001019df028 llvm::sys::PrintStackTrace(__sFILE*) + 40
1 swift 0x00000001019df514 SignalHandler(int) + 452
2 libsystem_platform.dylib 0x00007fff9a2dc5aa _sigtramp + 26
3 libsystem_platform.dylib 000000000000000000 _sigtramp + 1708276336
4 swift 0x0000000100fe90ea swift::ClangImporter::Implementation::loadAllMembers(swift::Decl const*, unsigned long long, bool*) + 3130
5 swift 0x0000000101da2834 swift::IterableDeclContext::loadAllMembers() const + 100
6 swift 0x0000000101d995dc swift::NominalTypeDecl::getMembers(bool) const + 28
7 swift 0x0000000101dc029f swift::NominalTypeDecl::lookupDirect(swift::DeclName) + 79
8 swift 0x0000000101dbe96a swift::DeclContext::lookupQualified(swift::Type, swift::DeclName, unsigned int, swift::LazyResolver*, llvm::SmallVectorImpl<swift::ValueDecl*>&) const + 3146
9 swift 0x0000000100fe5941 (anonymous namespace)::SwiftDeclConverter::VisitObjCPropertyDecl(clang::ObjCPropertyDecl const*, swift::DeclContext*) + 161
10 swift 0x0000000100fe0d0d clang::declvisitor::Base<clang::declvisitor::make_const_ptr, (anonymous namespace)::SwiftDeclConverter, swift::Decl*>::Visit(clang::Decl const*) + 3117
11 swift 0x0000000100fe005b swift::ClangImporter::Implementation::importDeclImpl(clang::NamedDecl const*, bool&, bool&) + 331
12 swift 0x0000000100fe4912 swift::ClangImporter::Implementation::importDeclAndCacheImpl(clang::NamedDecl const*, bool) + 226
13 swift 0x0000000100fe879e swift::ClangImporter::Implementation::loadAllMembers(swift::Decl const*, unsigned long long, bool*) + 750
14 swift 0x0000000101da2834 swift::IterableDeclContext::loadAllMembers() const + 100
15 swift 0x0000000101d99a95 swift::ExtensionDecl::getMembers(bool) const + 21
16 swift 0x0000000101dc027d swift::NominalTypeDecl::lookupDirect(swift::DeclName) + 45
17 swift 0x0000000101dbe96a swift::DeclContext::lookupQualified(swift::Type, swift::DeclName, unsigned int, swift::LazyResolver*, llvm::SmallVectorImpl<swift::ValueDecl*>&) const + 3146
18 swift 0x0000000101cc6288 swift::TypeChecker::lookupMember(swift::Type, swift::DeclName, swift::DeclContext*, bool) + 200
19 swift 0x0000000101c34e2c swift::constraints::ConstraintSystem::lookupMember(swift::Type, swift::DeclName) + 220
20 swift 0x0000000101c6b32d swift::constraints::ConstraintSystem::simplifyMemberConstraint(swift::constraints::Constraint const&) + 2173
21 swift 0x0000000101c6dc88 swift::constraints::ConstraintSystem::simplifyConstraint(swift::constraints::Constraint const&) + 216
22 swift 0x0000000101c354bc swift::constraints::ConstraintSystem::addConstraint(swift::constraints::Constraint*, bool, bool) + 28
23 swift 0x0000000101c5a8a5 swift::ASTVisitor<(anonymous namespace)::ConstraintGenerator, swift::Type, void, void, void, void, void>::visit(swift::Expr*) + 9317
24 swift 0x0000000101c5c502 (anonymous namespace)::ConstraintWalker::walkToExprPost(swift::Expr*) + 162
25 swift 0x0000000101d6627f (anonymous namespace)::Traversal::visit(swift::Expr*) + 6431
26 swift 0x0000000101d62765 swift::Expr::walk(swift::ASTWalker&) + 53
27 swift 0x0000000101c583b0 swift::constraints::ConstraintSystem::generateConstraints(swift::Expr*) + 96
28 swift 0x0000000101c90ab6 swift::TypeChecker::typeCheckExpression(swift::Expr*&, swift::DeclContext*, swift::Type, swift::Type, bool, swift::FreeTypeVariableBinding, swift::ExprTypeCheckListener*) + 518
29 swift 0x0000000101cd73e3 swift::ASTVisitor<(anonymous namespace)::StmtChecker, void, swift::Stmt*, void, void, void, void>::visit(swift::Stmt*) + 291
30 swift 0x0000000101cd64c3 swift::TypeChecker::typeCheckFunctionBodyUntil(swift::FuncDecl*, swift::SourceLoc) + 371
31 swift 0x0000000101cd6b8f swift::TypeChecker::typeCheckAbstractFunctionBody(swift::AbstractFunctionDecl*) + 95
32 swift 0x0000000101c86b65 typeCheckFunctionsAndExternalDecls(swift::TypeChecker&) + 421
33 swift 0x0000000101c87476 swift::performTypeChecking(swift::SourceFile&, swift::TopLevelContext&, unsigned int) + 1734
34 swift 0x0000000100fc07dd swift::CompilerInstance::performSema() + 2253
35 swift 0x0000000100d54831 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 1953
36 swift 0x0000000100d5294d main + 1677
37 libdyld.dylib 0x00007fff960e05fd start + 1
38 libdyld.dylib 0x0000000000000061 start + 1777465957
Stack dump:
0. Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Classes/NetClass/Downloader.swift -primary-file /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Vistas/Proyecto/MapaViewController.swift /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Vistas/Widget/ToggleView.swift /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Classes/Entities/Mapa.swift /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Classes/Entities/Edificio__c.swift .
.
.
.
.
1. While type-checking 'loadMapa' at /Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Vistas/Proyecto/MapaViewController.swift:56:5
2. While type-checking expression at [/Users/Fortis/Proyectos/IOS Apps/Abilia/Abilia iOS/Abilia/Abilia/Vistas/Proyecto/MapaViewController.swift:57:9 - line:57:29] RangeText="mapaView.delegate = s"
func loadMapa () {
mapaView.delegate = self
var theCoord = CLLocationCoordinate2DMake(0, 0)
if let coordenadasU = coordenadas {
let coordArray:[NSString] = coordenadasU.componentsSeparatedByString(",") as [NSString]
if coordArray.count > 1 {
let lat: CLLocationDegrees = coordArray[0].doubleValue;
let long: CLLocationDegrees = coordArray[1].doubleValue;
theCoord = CLLocationCoordinate2DMake(lat, long)
}
}
pointAnnotation.coordinate = theCoord;
mapaView.addAnnotation(pointAnnotation)
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region:MKCoordinateRegion = MKCoordinateRegion(center: theCoord, span: span)
mapaView.setRegion(region, animated: true)
mapaLoaded = true;
}
This is one of Swift's many bugs where the compiler suddenly crashes because of specific code in your app it cannot handle.
You have to isolate the problematic part (e.g. by commenting out parts of the screen) and once it compiles again find a workaround to use different code.
How does your method loadMapa look like? It's the cause the compiler mentioned.
I had same error when subclassing UIButton and overriding selected property like this:
class ActionButton: UIButton {
override var selected: Bool = true {
didSet {
updateBackgroundColor()
}
}
}
Solution was to remove ' = true' from the override statement:
class ActionButton: UIButton {
override var selected: Bool {
didSet {
updateBackgroundColor()
}
}
}
I'm just guessing but I would double-check if you implemented your delegate method exactly right way... With all exclamation marks correctly given... '!' at the end of MKAnnotationView! seems to be a bit suspicious.
I've searched why The error: "Command failed due to signal: Segmentation fault: 11" is causing problems in my app... My app is Parse dependent. I found out that Parse made changes to method:
query.findObjectsInBackgroundWithBlock({ (objects : [AnyObject]?, error : NSError?) -> Void in
to
query.findObjectsInBackgroundWithBlock({ (objects : [**PFObject**]?, error : NSError?) -> Void in
I've changed it all, and now it works. Hope this will help someone using Parse. Cheers
Not really a specific answer, but I wanted to add another possible cause of this bug (since it's still quite common).
My program had code like so:
if (myArray.count > 0) && (.Foo != myArray.last) {
// Do something
}
In my case .Foo belonged to an enum for which I'd implemented Equatable, however, for some reason the Swift compiler didn't highlight my comparison to myArray.last as an error (non-optional compared to optional) and produced a segmentation fault.
In my case the fix was simply to use myArray.last! since the myArray.count > 0 ensures this will always succeed (must be at least one element).
As usual, once you know what the bug is, be sure to pass it on to bug report.apple.com!

Resources