D9539b77128607ecc9295106487d4e5c
Swift 和 Nullable 的坑

这两天我们遇到了一个非常神奇的 Bug,这个 Bug 在 Debug 环境不会出现,只有在 Release 包中才会出问题。并且排除了 DEBUG 宏的影响。最终发现是一个错误的 Nullable 标记,导致 Swift 在进行编译优化时移除了一句 if 语句。特此记录

最初正常的代码

最初的代码是这样的:

// AnOCClass.h
#import <Foundation/Foundation.h>

@interface AnOCClass : NSObject
- (void)doSomeThingWithCompletionBlock:(void (^)(NSError *error, NSUInteger result))completionBlock;
@end


// AnOCClass.m
#import "AnOCClass.h"

@implementation AnOCClass
- (void)doSomeThingWithCompletionBlock:(void (^)(NSError *error, NSUInteger result))completionBlock {
    // In fact, everything is ok. Error is nil.
    completionBlock(nil, 1);
}
@end

```swift
// ASwiftClass.swift
import Foundation

public class ASwiftClass: NSObject {
@objc public func triggerTheBug() {
let anOCObject = AnOCClass()
anOCObject.doSomeThing { (error, result) in
if error == nil { // <-------------------- Notice
print("result is \(result)")
} else {
print("something go wrong")
}
}
}
}

top Created with Sketch.