Switch and @avaliable

Given the following enum:

enum Labels: String {
    
    case foo
    case bar
    case baz

    @available(iOS 14, *)
    case notAvailableYet
    
}

With the following code:

@avaliable(iOS14, *)
fun foo() {
}

switch label {

case . notAvailableYet:
      foo()
}

The compiler will force you to wrap the call-site for foo() with a availability check even that case is already for an enum which is marked as only being available for the same iOS version.

It would be great if the compile could automatically synthesise this availability check as part of the case statement so it won't execute that case (If rawValue was used to dynamically select that enum then perhaps there could be a runtimes error)

Otherwise if this isn't possible for reasons of explicitness then it would be great to have some syntax sugar to clean up the code

So this:

switch label {

    case . notAvailableYet:
          if #avaliable(iOS 14, *) {
             foo()
          }
}

Can become something like this:

switch label {

@avaliable(iOS14, *)
case . notAvailableYet:
      foo()

}

5 Likes

Definitely reasonable! It's been filed as SR-4079, but no one's quite gotten to it yet—though the original phrasing of SR-4079 says there'd be no annotation, rather than allowing @available on the case. I think I like your version better since it's explicit about what's happening, but we'd need rules about what happens if the availability doesn't match the case in question.

4 Likes

I think it should just be kept simple for now and that the annotation should be identical to the annotation on the original declaration for that case.

So that if you change the availability check it's immediately apparent where code needs to be updated.

These restrictions could be loosened over time if needed.

1 Like
Terms of Service

Privacy Policy

Cookie Policy