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

Unable to use protocol with class type where AnyObject is expected

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Duplicate
    • Component/s: None
    • Labels:
      None

      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

       

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              stemichels Stephan Michels
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: