Uploaded image for project: 'Swift'
  1. Swift
  2. SR-14943

Fix-it for changing unsafeBitcast to unsafeDowncast should be more narrow or removed

    XMLWordPrintable

    Details

      Description

      According to the documentation, unsafeBitcast expects that the target type is layout-compatible with the type of the value passed in.

      OTOH, unsafeDowncast expects that the type of the value is the target type (there is a _debugPrecondition(x is T)).

      Currently, we have a fix-it where we recommend replacing unsafeBitcast with unsafeDowncast. However, strengthening a precondition like that in a fix-it is generally not OK unless we have some reason to believe that x is T will be true.

      Here is a code example that can be tested in a playground:

      import Foundation
      import UIKit
      ​
      @propertyWrapper
      struct UnsafeBitCast<Actual: NSObjectProtocol, Mocked: NSObjectProtocol> {
          init(wrappedValue: Actual?, to mocked: Mocked.Type) {
              self.wrappedValue = wrappedValue
          }
          var wrappedValue: Actual?
          var projectedValue: Mocked? {
              wrappedValue.map({ unsafeBitCast($0, to: Mocked.self) }) // fix-it suggests unsafeDowncast
          }
      }
      ​
      class MockUIWindow: NSObject {
          @UnsafeBitCast(to: UIScene.self) var mockWindowScene: MockUIScene? = nil
          init(mockWindowScene: MockUIScene? = .init()) {
              self.mockWindowScene = mockWindowScene
          }
          var windowScene: UIScene? {
              $mockWindowScene
          }
      }
      ​
      class MockUIScene: NSObject {
          @objc var activationState: UIScene.ActivationState
          init(activationState: UIScene.ActivationState = .foregroundActive) {
              self.activationState = activationState
          }
      }
      ​
      let mockWindow = MockUIWindow()
      print(mockWindow.windowScene!.activationState == .foregroundActive)
      

      If one applies the fix-it, this code crashes due to the precondition failing. We should either remove the fix-it altogether or only apply it narrowly in the cases where we know for sure that x is T will be true.

        Attachments

          Activity

            People

            Assignee:
            Rajagopalan Rajagopalan Gangadharan
            Reporter:
            typesanitizer Varun Gandhi
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated: