private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
extension NSNumber {
var isBool: Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
|| (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
代码来自于SwiftyJSON
可见每一个NSNumber(继承自NSValue)都有一个objCType属性,标明其Objective-C数据类型。OC中可以用@encode编译器命令。具有同样效果。SwiftyJSON中写得这么啰嗦一定是为了可读性。
- (void)someMethod {
char *intCharArray = @encode(int);
char *boolCharArray = @encode(BOOL);
if (strcmp(intCharArray, boolCharArray) == 0) {
NSLog(@"两个字符串相等");
}
}