Search code examples
swiftsyntaxprotocols

Class does not conform to protocol. Why?


class Controller<U: NSObject> {}

protocol Robert {
  associatedtype T
  associatedtype U: Controller<T>
  var fetcher: U { get }
}

class Telephone: NSObject {}

class Object: Telephone {}

class Turtle: Controller<Object> {}

class Fish: Robert {

  typealias T = Object
  typealias U = Turtle

  let x = Turtle()

  var fetcher: Turtle {
    return x
  }

}

I don't understand why. Any help appreciated.

When selecting the XCode 'fix it' option, a stub for 'Fetcher is inserted. But there is already a typealias for Fetcher.


Solution

  • This has now been recognized as a bug in Swift 4. For now we must avoid associated types constrained by types that have generic constraints.

    So this is not cool

    associatedtype U: Controller<T>
    

    Removing it results in the following, which works.

    protocol Robert {
      associatedtype T: NSObject
      var fetcher: Controller<T> { get }
    }