objective-c - Decimal 在 Swift 3 中作为 NSDecimal 而不是 NSDecimalNumber 导入到 Objective C

标签 objective-c swift swift3

我在 Swift Decimal 和 Objective C NSDecimalNumber 之间进行类型转换时遇到问题。

如果我有 Swift 类:

@objc class Exam: NSObject {
    var grade: Decimal = 90.0
}

并尝试在 Objective C 中使用该 Swift 类,

Exam *exam = [[Exam alloc] init];
NSDecimalNumber *result = [[NSDecimalNumber zero] decimalNumberByAdding:grade.value];

我得到错误:

Sending 'NSDecimal' to parameter of incompatible type 'NSDecimalNumber * _Nonnull'

似乎 grade 被视为 NSDecimal 而不是 NSDecimalNumber。根据 这似乎是不正确的它说

The Swift overlay to the Foundation framework provides the Decimal structure, which bridges to the NSDecimalNumber class. The Decimal value type offers the same functionality as the NSDecimalNumber reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes.

所以我不确定 1) 我做错了什么。 2) 文档中有错误或 3) 这是一个 Swift 错误。

我不想在我的 Swift 类 NSDecimalNumber 中显式创建值,因为这样我就无法在不执行整个丑陋的 的情况下进行简单的算术运算,例如 + >decimalNumberByAdding 跳舞。

最佳答案

似乎 DecimalNSDecimalNumber 的桥接功能不像 StringNSString 那样工作,或者 ArrayNSArray。但它更像是 IntNSNumber

您不会期望 Swift 中的 Int 属性可以像 Objective-C 中的 NSNumber 一样访问。

如何添加一个用于 Objective-C 的 getter:

extension Exam {
    @objc var gradeValue: NSDecimalNumber {
        return grade as NSDecimalNumber
    }
}

您可以在 Objective-C 中像这样使用它:

Exam *exam = [[Exam alloc] init];
NSDecimalNumber *result = [[NSDecimalNumber zero] decimalNumberByAdding:exam.gradeValue];

关于objective-c - Decimal 在 Swift 3 中作为 NSDecimal 而不是 NSDecimalNumber 导入到 Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40556661/

相关文章:

objective-c - -[NSInvocation retainArguments] 是否复制 block ?

ios - 使用 Self 作为泛型参数

ios - 如何使用 AWS Rekognition 在 Swift 3 中检测图像标签和人脸

ios - 带有协议(protocol)的自定义 Cell,用于检查 UISwitch 中的更改

ios - 分别关闭 ViewCntroller 的两个实例 Swift 3.0

iOS - 在 scaleaspectfit UIImageView 的图像上布局 UIImageView 的 subview

ios - UIBezierPath 点在路径的一部分

objective-c - 将 Xcode 4.5 新的 XIB 文件恢复到 iOS<6

ios - UICollectionViewCell 捏合中的 CALayer

swift - 从函数内的各个循环返回一个值