我在 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
最佳答案
似乎 Decimal
和 NSDecimalNumber
的桥接功能不像 String
和 NSString
那样工作,或者 Array
和 NSArray
。但它更像是 Int
和 NSNumber
。
您不会期望 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/