[swift-evolution] Swift's Optional Int as NSNumber in Objective-C
David Waite
david at alkaline-solutions.com
Sat May 20 16:15:30 CDT 2017
> On May 20, 2017, at 12:47 PM, Philippe Hausler <phausler at apple.com> wrote:
>
> With the introduction of SE-0170 the behavior is a bit more predicable: The rule is that if the value would not loose mantissa representation or significant bits of the representation it will bridge to the target type in all scenarios, no matter if it is created in objc or in swift.
>
>> On May 19, 2017, at 9:00 PM, David Waite via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>
>> When I call such a mapped Swift API that expects an Int? parameter from Objc with a NSNumber initialized with 3.5, what should happen?
>
> NSNumber(value: 3.5) as? Int == nil
>
> But
>
> NSNumber(value: 3.5).intValue == 3
as? now has the closest to predictable behavior, but I would argue that in terms of generalizing a transform, the meaning of ‘nil’ for an Int? parameter may not match the behavior one would expect passing in a value which was not an integer value - say using 3.00000000004 as the argument (due to rounding errors) rather than the integer 3.
The safest default behavior (should a nullable NSNumber be used to represent an Int? parameter) would probably be to fatalError out if the user passed a NSNumber with a value which was not exactly an Int. No NSNumber instance would be interpreted as ‘nil’ once bridged into Swift.
This still allows the odd edge case of a boolean value being interpreted as 1, which could cause interface comprehension issues if Bool? was also mapped to NSNumber in Objc interfaces.
-DW
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170520/ad5a34c5/attachment.html>
More information about the swift-evolution
mailing list