[swift-evolution] [Proposal draft] Bridge Optional As Its Payload Or NSNull

Charlie Monroe charlie at charliemonroe.net
Wed Aug 24 23:23:03 CDT 2016


> On Aug 25, 2016, at 5:00 AM, Charles Srstka via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> On Aug 24, 2016, at 8:27 PM, Greg Parker via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>>> On Aug 23, 2016, at 3:36 PM, Douglas Gregor via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>> 
>>> Proposed solution
>>> 
>>> When an Optional<T> value is bridged to an Objective-C object, if it contains some value, that value should be bridged; otherwise, NSNull or another sentinel object should be used.
>>> 
>> I don't think I like this.
>> 
>> Let me verify my understanding. If I have this:
>> 
>>     // imported from ObjC
>>     func f(with object: Any)
>>     
>>     let s: String? = nil
>>     f(s)
>> 
>> then at runtime it will call 
>>     f([NSNull null])
>> ?
>> 
>> The problem is that NSNull is in fact rare in Cocoa. They are used in the Foundation containers and almost nowhere else. Passing NSNull into almost any API is going to do something confusing at runtime. If you're lucky you get a prompt error "-[NSNull something]: unrecognized selector". If you're not lucky you'll get that error somewhere much later, or something even less obviously related to NSNull and your call site. That sounds like the wrong outcome for developers who are confused or careless or unaware of an optional.
> 
> I agree, particularly since passing an array of optionals to an Objective-C API is much more likely to be the result of a typo or other programmer error than something actually intentional that ought to invoke the bridge.

Agreed. I was going back and forth on this proposal and I think there still is a lot of unaudited API (untyped NSArray/NSDictionary) out there that simply expects some type of values and this is very error-prone to passing in NSNull, which personally was the worst nightmare for me when dealing with JSONs in ObjC - that I pass NSNull instead of NSString somewhere; since this is an issue that can - as Charles mentioned - reveal itself much much later and is then hard to debug - in such cases, I'd strongly prefer the app crashing at call site.

> 
> Charles
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160825/129c08a4/attachment.html>


More information about the swift-evolution mailing list