How to check for NSDecimalNumber.zero() in Swift
Asked Answered
A

3

6

Using 'num1' as a comparison reference to determine if 'num2' or 'num3' are zero. Have done this successfully in Objective-C, and am trying to do it in Swift:

let num1: NSDecimalNumber = NSDecimalNumber.zero()
let num2: NSDecimalNumber = NSDecimalNumber.decimalNumberWithString("0")
let num3: NSDecimalNumber = NSDecimalNumber.decimalNumberWithString("0.000001")

if num1.compare(num2) == NSOrderedSame {
    println("They match")
}

This attempt results in: "error: use of unresolved identifier 'NSOrderedSame'." What is the proper way to accomplish this in Swift? (Have searched the book and web, but missing something possibly obvious, thank you).

Anchises answered 14/6, 2014 at 19:27 Comment(0)
P
15

Do you mean: num1.compare(num2) == NSComparisonResult.OrderedSame

Polychromy answered 14/6, 2014 at 19:33 Comment(2)
Yes! Thank you, that's exactly what I was looking for. Now to learn how to find that myself in the apple documentation : )Anchises
Swift can infer the NSComparisonResult so you can drop it (still need the .)Thomas
B
7

in Swift that can happen an easier way, like e.g. this:

    if num1 == num2 {
        println("They match")
    }

BACKGROUND

(extracted from Using Swift Cocoa and Objective-C APIs, Object Comparison section)

Swift and Objective-C objects are typically compared in Swift using the == and === operators. Swift provides a default implementation of the == operator for objects that derive from the NSObject class. In the implementation of this operator, Swift invokes the isEqual: method defined on the NSObject class.

Bolshevism answered 14/6, 2014 at 19:47 Comment(7)
Are you sure this is true about NSNumber objects?Guelph
I could not find the reference currently (I will) but the Swift automatically converts those == opreators to an -isEqual: method for Obj-C objects, like e.g. NSNumbers.Bolshevism
I'm trying to find it again... to be fair, in the last two weeks I've been reading all possible documentation of Swift and I have no idea where I found it... but I will find it again, because that would be a very useful information.Bolshevism
According to my test, it appears to work, will look for the reference also. (I haven't tested for the cases of NSOrderAscending and NSOrderDescending though).Anchises
@LeoNatan, I found the reference again, and I've added to my answer.Bolshevism
@H_H, I've attached the reference. :)Bolshevism
@LeoNatan, Thank you! I should try the <, >, <=, and >= comparisons too, they might work just as well.Anchises
L
2

If you're working with NSDecimalNumber often, I'll plug my own operator overloads here: https://gist.github.com/anisoptera/5708afc32454ed868363

Takes care of that irritating unclear "NSOrdered..." comparison and even lets you do such crazy things as add two NSDecimalNumbers with the + operator!

Lymphocyte answered 17/6, 2014 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.