快速检查NSNumber是否为Double

时间:2019-05-24 12:04:40

标签: ios swift nsnumber

所以我试图检查NSNumberDouble还是Int,但我想知道是否有可能。

我希望这能起作用,但是无论我比较哪种类型,它总是返回true

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中,我正在使用数字扩展名,该扩展名是NSNumber,我想迅速创建它

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()
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用低级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)
            }
        }
    }
}

答案 1 :(得分:0)

尝试此代码。

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")
}