0
protocol AClass: class {
    
}

class Controller {
    
    let classes: [AClass] = []
    
    
    init() {
        self.upload(classes: self.classes)
    }
    
    
    func upload<C: AClass>(classes: [C]) {
        
    }
}

The line in the initializer has a compile-time error of:

Value of protocol type 'AClass' cannot conform to 'AClass'; only struct/enum/class types can conform to protocols

Why? The protocol can only be applied to a class. Do I need to tell the compiler something more?

Jon Vogel
  • 5,244
  • 1
  • 39
  • 54
  • 1
    See https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself Anyway, why does `upload` need to be generic? This seems to be a misuse/misunderstanding of generics... – Sweeper Nov 24 '20 at 00:22
  • You have defined a method that takes an array of objects that conform to AClass. These need to be concrete objects, but the self.classes property you are using as the input value to the method is an array of protocol-conforming "somethings" not the actual concrete types that conform to the protocol. – flanker Nov 24 '20 at 01:52

1 Answers1

0

When using generics (func upload<C: AClass>(classes: [C])), you ask for a generic type that conform to the protocol AClass.

However, in Swift a protocol doesn't conforms to itself, so using classes (which is AClass protocol) doesn't match the generic requirement (conforming to AClass).

In your case, I don't see the benefit of using a generic for the upload method. You can just use AClass protocol here:

class Controller {
    
    let classes: [AClass] = []
    
    
    init() {
        self.upload(classes: self.classes)
    }
    
    
    func upload(classes: [AClass]) {
        // here you can use any property / method defined in `AClass` protocol.
    }
}
rraphael
  • 10,041
  • 2
  • 25
  • 33
  • Thank you, if `AClass` all of a sudden had "Self or associated type requirements" then it would have to be specified the previous way. But you are right, as written using the type directly compiles. – Jon Vogel Nov 24 '20 at 18:52
  • Yes, but I don’t see any Self requirement or associated type in your case, so you might want to go with the protocol directly – rraphael Nov 24 '20 at 19:10