Swift 检查 NSNumber 是否为 Double

Swift check if NSNumber is Double

所以我正在尝试检查 NSNumberDouble 还是 Int,我想知道这是否可能。

我希望这会奏效,但无论我比较哪种类型,它总是 returns 正确

var myDouble: Double = 0.0
var myNSNumber: NSNumber = NSNumber(value: myDouble)

if myNSNumber is Double {
    print("NSNumber is Double")
}else {
    print("NSNumber is different type")
}

在 kotlin 中,我在 swift 中使用 NSNumber 这样的数字扩展,我想在 swift

中重新创建它
protected operator fun Number.plus(other: Number): Number {
    return when (this) {
        is Long -> this.toLong() + other.toLong()
        is Int -> this.toInt() + other.toInt()
        is Short -> this.toShort() + other.toShort()
        is Byte -> this.toByte() + other.toByte()
        is Double -> this.toDouble() + other.toDouble()
        is Float -> this.toFloat() + other.toFloat()
    }
}

您可以使用 low-level CoreFoundation API:

获取存储的号码类型
extension NSNumber {
    var type: CFNumberType {
        return CFNumberGetType(self as CFNumber)
    }
}

然后就可以使用了

你的 plus 函数应该是这样的:

extension NSNumber {
    func plus(other: NSNumber) -> NSNumber {
        switch type {
        case .sInt8Type, .charType:
            return NSNumber(value: self.int8Value + other.int8Value)
        case .sInt16Type, .shortType:
            return NSNumber(value: self.int16Value + other.int16Value)
        case .sInt32Type, .longType:
            return NSNumber(value: self.int32Value + other.int32Value)
        case .sInt64Type, .longLongType:
            return NSNumber(value: self.int64Value + other.int64Value)
        case .float32Type, .floatType:
            return NSNumber(value: self.floatValue + other.floatValue)
        case .float64Type, .doubleType:
            return NSNumber(value: self.doubleValue + other.doubleValue)
        case .intType, .cfIndexType, .nsIntegerType:
            return NSNumber(value: self.intValue + other.intValue)
        case .cgFloatType:
            switch MemoryLayout<CGFloat>.size {
            case 4:
                return NSNumber(value: self.floatValue + other.floatValue)
            default:
                return NSNumber(value: self.doubleValue + other.doubleValue)
            }
        }
    }
}

试试这个代码。

var myDouble: Double = 0.0
var myNSNumber: NSNumber = NSNumber(value: myDouble)

if myNSNumber.isKindOfClass(Double) {
    print("NSNumber is Double")
} else {
    print("NSNumber is different type")
}