[swift-users] Different behaviour when casting Float and Double to NSNumber

Joe Groff jgroff at apple.com
Wed Oct 5 12:31:45 CDT 2016


> On Oct 5, 2016, at 2:30 AM, Lars-Jørgen Kristiansen via swift-users <swift-users at swift.org> wrote:
> 
> I'm working with a third party API for some external hardware. One of the functions takes a NSNumber, and it fails to interact correctly with the hardware if I cast a Float too NSNumber, but works as expected if I use Double..
> 
> I dont know if it is related to NSNumber.stringValue since I dont know what the third part lib does with the NSNumber, but I noticed this:
> 
> let float = 100_000_00 as Float
> let floatNumber = float as NSNumber
> 
> let double = 100_000_00 as Double
> let doubleNumer = double as NSNumber
> 
> hardware.doThing(number: floatNumber as NSNumber) // Hardware does not work
> hardware.doThing(number: doubleNumer as NSNumber) // Hardware works
> 
> // Also noticed this:
> "\(floatNumber)" // "1e+07"
> "\(doubleNumer)" // "10000000"
> 
> Is this expected behaviour?

cc'ing Tony and Philippe, who might be able to comment on the intended behavior of NSNumber here. When you cast using `as`, Swift will do the conversion through its Objective-C bridge, and will attempt to use a custom subclass of NSNumber that remembers the exact Swift type it was bridged as, such as Float or Double. There's a small chance your library is making assumptions that it's working with one of the standard NSNumber subclasses used by the Foundation implementation. If you call the NSNumber initializer `NSNumber(value: floatNumber)` instead of using the `as` conversion, you'll get one of these standard NSNumbers instead of a Swift-bridged NSNumber. Try that and see if it works. If using the initializer does indeed fix the problem, we'd appreciate a bug report, so we can investigate fixing the incompatibility with our NSNumber subclasses.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161005/637b99c6/attachment.html>


More information about the swift-users mailing list