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

David Sweeris davesweeris at mac.com
Sat Jan 13 19:28:12 CST 2018


> On Jan 11, 2018, at 22:15, 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()
> 
> 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`?

“Toggle” works for me, if we go this route.

I have a question about the idea, though... Why limit this to Bools? In principle, as long as there aren’t any associated values involved, shouldn’t we be able to iterate through any exhaustive enum type? Bools are an obvious example of a case where “x.nextCase” is useful, but should we consider whether we ought to instead give this functionality to all enums that don’t have associated values?

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20180113/24b8e126/attachment.html>


More information about the swift-evolution mailing list