10.4 C
Canberra
Friday, September 20, 2024

The (Swap) Case of the Lacking Binding — Erica Sadun


Right here’s a cool little problem introduced up this morning by a good friend. Contemplate the next code:

change foo {
  case .a: return "a"
  case .b(let str) the place str.hasPrefix("c"), .c: return "c"
  case .b: return "b"
}

It gained’t compile.

If you bind an emblem for one sample, you will need to bind that image for each sample in a case. This prevents you, for instance, from binding str in a single sample after which trying to make use of str within the shared case physique. For instance, contemplate this case. What would you count on to occur when foo is .c?

func switchTheFallthroughOrder(foo: Foo) -> String {
    change foo {
    case .a: return "a"
    case .b(let str) the place str.hasPrefix("c"), .c:
        // Utilizing `str` right here is dangerous!
        print(str)
        return "c"
    case .b: return "b"
    }
}

Regardless of my first knee-jerk refactoring, transferring out the .c case to make use of fallthrough doesn’t work. Once more, it’s because str just isn’t certain for .c and may be used within the successive case physique:

Nevertheless, as Greg Titus identified, if you happen to change the order to make use of the binding case first with fallthrough, Swift is aware of at compile time that the binding gained’t keep on past that scope. This resolves the error, since str is simply used within the the place clause to slender the sample matching:

Additional, when utilizing bindings in case exams, a waterfall strategy the place the certain gadgets are used earlier than fallthrough can lengthen by way of a number of steps with the blessing of the compiler:

case .widest(let first, let second) the place first.satisfiesACondition():
    // can use `first`, `second` right here
    fallthrough
case .medium(let second) the place second.satisfiesAnotherCondition():
    // can use `second` right here even when it was certain 
    // by way of `widest` above by way of fallthrough
    fallthrough
case .narrowest: return someValue

My because of Greg Titus for figuring this all out!



Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles