[英]Swift Overload NSDecimalNumber operators
I'm wondering if there is a reason Swift doesn't just overload the standard arithmetic (+,-,*,<,> etc.) operators for NSDecimalNumber
, and instead opts for traditional methods with names like adding
, subtracting
etc.我想知道 Swift 是否有理由不只是重载
NSDecimalNumber
的标准算术(+、-、*、<、> 等)运算符,而是选择具有诸如adding
、 subtracting
等名称的传统方法。
I'd like to overload these operators, is this a good idea, what are the potential drawbacks?我想重载这些运算符,这是一个好主意,潜在的缺点是什么?
EDIT编辑
Apparently Swift 3 added a Decimal
type.显然 Swift 3 添加了
Decimal
类型。 Swift 3 also dropped NS in front of a bunch of other types so I assumed Decimal
was just an NSDecimal
with the NS dropped, but this is not the case, Although it doesn't really answer the question, I think using Decimal
instead of NSDecimalNumber
should usually be a good response going forward for Swift 3 and later. Swift 3 也将 NS 放在一堆其他类型的前面,所以我认为
Decimal
只是一个NSDecimal
而 NS 被丢弃,但事实并非如此,虽然它并没有真正回答问题,但我认为使用Decimal
而不是NSDecimalNumber
对于 Swift 3 及更高版本,通常应该是一个很好的响应。 One reason you may want to stick with NSDecimalNumber
is if you have many extensions and don't want to bridge every time you want to use extension methods.您可能要坚持使用
NSDecimalNumber
的一个原因是,如果您有很多扩展并且不想在每次使用扩展方法时都进行桥接。
Have you though about using Decimal
instead of NSDecimalNumber
? 您是否要使用
Decimal
而不是NSDecimalNumber
?
let d1 = Decimal(integerLiteral: 10)
let d2 = Decimal(integerLiteral: 2)
let result = d1 * d2 // 20
I have to retain the old NSDecimalValue to use with Core Data.我必须保留旧的 NSDecimalValue 才能与 Core Data 一起使用。 I wanted to be able to use comparisons, so I added this extension:
我希望能够使用比较,所以我添加了这个扩展:
extension NSDecimalNumber: Comparable { // Comparable adds <=, >=, and >
public static func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .orderedSame
}
public static func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.