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

A `protocol A: class` is not any `AnyObject`

    XMLWordPrintable

    Details

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

      Xcode 9 release, fails in both Swift 3.2 and 4.0.

      Description

      I want to restrict a function to only work w/ reference types. In protocols this is expressed using `protocol A : class` and in generics as `T: AnyObject`. So I assumed this would work:

      //: Playground - noun: a place where people can play
      
      protocol AwesomeKind : class {}
      class    Awesome     : AwesomeKind {}
      
      let a   =   Awesome()
      let b   =   Awesome()
      var arr : [ Awesome ] = [ a, b ]
      
      func idxIndenticalTo<T: AnyObject>(arr: [ T ], item: T) -> Int? {
        return arr.index(where: { $0 === item })
      }
      
      let i = idxIndenticalTo(arr: arr, item: b) //1
      
      let c    :   AwesomeKind   = Awesome()
      let d    :   AwesomeKind   = Awesome()
      var arr2 : [ AwesomeKind ] = [ c, d ]
      let k = idxIndenticalTo(arr: arr2, item: d) //1
        // error: cannot convert value of type '[AwesomeKind]' to expected argument type
        // or
        // error: cannot invoke 'idxIndenticalTo' with an argument list of type '(arr: [AwesomeKind], item: AwesomeKind)'
      

      Why is a `protocol A: class` not an `AnyObject`? It should be exactly the same?

      But OK, so lets assume `AnyObject` is something different. And indeed I can do this:

      protocol AwesomeKind:class,AnyObject {}
      

      But this still results in the same issue.

      I'm pretty sure this is a bug or oversight, don't know

      P.S. My real code goes more like this, but the above is the easier version:

      public extension Array where Element : AnyObject {
        public func indexSetForObjectsIdentical<S: Sequence>(to objects: S)
                      -> IndexSet
                      where S.Element : AnyObject
      

      Which produces

      // error: 'MyCoolClassProtocolType' is not convertible to 'AnyObject'
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              slavapestov Slava Pestov
              Reporter:
              helge Helge Heß
              Votes:
              0 Vote for this issue
              Watchers:
              7 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: