[swift-evolution] [pitch] adding toggle to Bool

Cheyo Jimenez cheyo at masters3d.com
Fri Jan 12 10:29:38 CST 2018



> On Jan 12, 2018, at 12:14 AM, Nate Cook via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Jan 12, 2018, at 12:15 AM, Chris Eidhof via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> Hey SE!
>> 
>> When we have a bunch of nested structs:
>> 
>>     struct Sample {
>>         var bar: Bar
>>     }
>>     
>>     struct Bar {
>>         var show: Bool
>>     }
>>     
>>     var foo = Sample(bar: Bar(show: false))
>> 
>> It can be repetitive to toggle a deeply nested boolean:
>> 
>>     foo.bar.show = !foo.bar.show // duplication
>> 
>> I sometimes add a `toggle` extension on `Bool`
>> 
>>     extension Bool {
>>         mutating func toggle() {
>>             self = !self
>>         }
>>     }
>> 
>> This allows you to write the same code without duplication, and makes the intent clearer:
>> 
>>     foo.bar.show.toggle()
> 
> I like it!
> 
>> In other languages, I don't think the `toggle` would make as much sense, but the mutable self makes this very useful.
>> 
>> After I posted it on Twitter, it turns out I'm not the only one: https://twitter.com/PublicExtension/status/730434956376346624
>> 
>> I would have gone straight to a proposal, but I think we can do some bikeshedding about the name of `toggle`?
> 
> Another verb that could work is `invert`.

That’s a good one. Similar to bit flipping which Apple calls inverting. 

“The bitwise NOT operator (~) inverts all bits in a number:”

I was thinking `flip` for this function but then I actually don’t think this extension is a good idea in the standard library :(

Should we also have a mutating extension for the `NOT` operator? Probably no. 

If people need it, they can add it and call it toggle, invert, flip, reverse, negate or what ever they want.  

It’s a slippery slope because it makes me want to have something like `not()` added to the library. I don’t think it’s worth it. 



> 
> The `!` operator that does this is the negation operator, but I think `negate` could sound to some like "make this false" rather than toggling. 
> 
> Nate
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20180112/3c55773f/attachment.html>


More information about the swift-evolution mailing list