Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-8624] Unable to use protocol with class type where AnyObject is expected #51139

Closed
swift-ci opened this issue Aug 23, 2018 · 1 comment
Closed
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.

Comments

@swift-ci
Copy link
Collaborator

Previous ID SR-8624
Radar None
Original Reporter stemichels (JIRA User)
Type Bug
Status Resolved
Resolution Duplicate
Additional Detail from JIRA
Votes 0
Component/s
Labels Bug
Assignee None
Priority Medium

md5: 276e572a066726a6c8b6de639e3070f8

duplicates:

  • SR-55 non-@objc protocol existentials do not conform to their own protocol type

Issue Description:

I'm not sure if this is a bug or an expected behaviour, but for me this seems wrong.

I have a class with a generic type that needs to be an object. And I cannot use a protocol with an class type as type for this class.

class Holder<T: AnyObject> {
    var value: T? = nil
    
    init() {
        self.value = nil
    }
    
    init(_ value: T) {
        self.value = value
    }
}

protocol ObjectWithValue: class {
    var string: String { get }
}

class MyObject: ObjectWithValue {
    var string: String = "test"
}

let object = MyObject()
let holder1 = Holder(object)

let objectByProtocol: ObjectWithValue = object
let holder2 = Holder(objectByProtocol) // <- Error


let holder3 = Holder<ObjectWithValue>() // <- Error
holder2.value = object

With Xcode 10 Beta 6 I get following errors:

ClassType.playground:25:15: Cannot invoke initializer for type 'Holder<_>' with an argument list of type '(ObjectWithValue)'

ClassType.playground:27:15: 'Holder' requires that 'ObjectWithValue' be a class type

@belkadan
Copy link
Contributor

A protocol value doesn't have the same representation as a class instance; it needs an extra pointer to carry around how the instance conforms to the protocol. So it's not compatible with the generic parameter here.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.
Projects
None yet
Development

No branches or pull requests

2 participants