swift icon indicating copy to clipboard operation
swift copied to clipboard

[SR-2146] Crash when @objc protocol existential is cast to another type and back in generic context

Open jadengeller opened this issue 10 years ago • 3 comments

Previous ID SR-2146
Radar None
Original Reporter @jadengeller
Type Bug
Status Resolved
Resolution Done

Environment

Swift 2.2

Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug, RunTimeCrash
Assignee None
Priority Medium

md5: f13672703fe6c8f14099dcba6e9aeb7b

Issue Description:

The following crashes with the error "Could not cast value of type 'SwiftObjCProtocolBug.Test' (0x1002c6988) to 'SwiftObjCProtocolBug.Foo' (0x1005fd040)."

import Foundation

@objc protocol Foo { }
protocol Bar: Foo { }
class Test: Bar { }

func magic<T: Foo>(x: T) -> T {
    let y = x as Any
    return y as! T
}

print(magic(Test() as Foo))

Workaround: Add a redundant conformance to `Foo` when `Test` is declared. Oddly, the compiler doesn't warn us about this. Note that the redundant conformance cannot be added in an extension due to SR-2078.

jadengeller avatar Jul 22 '16 01:07 jadengeller

Still broken in Swift 3 (with the necessary argument label change).

belkadan avatar Jul 22 '16 17:07 belkadan

I believe this is fixed in or before Xcode 9.4.1's toolchain's Swift version.

Dante-Broggi avatar Jul 16 '18 13:07 Dante-Broggi

Resolving as the provided code does not crash for me, and no one has responded since I asked.

Dante-Broggi avatar Sep 30 '18 20:09 Dante-Broggi