3

So the idea is: I have a subclass (of NSView for instance) called an AmazingViewClass and I want to store a member of a generic type called AmazingData.

AmazingData is defined as:

protocol AmazingDataType {}

class  AmazingData <x:CustomStringConvertible, y:Hashable>: AmazingDataType {
    var xValues: x
    var yValues: y
    init(xValues: x, yValues: y) {
        self.xValues = xValues
        self.yValues = yValues
    }
}

Then I have a protocol that can only be applied to NSView subclass:

protocol AmazingViewProtocol  {
    associatedtype View: NSView = Self //AmazingViewProtocol can only be applied to NSView
    associatedtype myType: AmazingDataType //so that data can only be of type AmazingDataType
    var data: myType! { get set }
}

And finally I declare a class AmazingViewClass

class AmazingView: NSView, AmazingViewProtocol {

}

However, it doesn't allow me to do that, requiring to specify the type of data variable like so:

class AmazingView: NSView, AmazingViewProtocol {
    typealias myType = AmazingData <Int, Int>
    var data: AmazingData <Int, Int>!
}

What I want to avoid is declaring the AmazingViewClass as AmazingViewClass <Type,Type> and set the data to any type I want later after initializing AmazingView like:

let data = AmazingData<Int, Double>()
... 
var aView = AmazingView(frame: CGRect...)
aView.data = data

So is there any way to achieve it? Or the compiler will never allow me to create a class without explicitly specifying a type of a generic variable?

Alexei
  • 511
  • 1
  • 10
  • 22
  • 1
    So you want to be able to specify for each `AmazingView` instance the type of `myType`? Basically you want to conform your class to the protocols associated type requirement in a generic way? – Dávid Pásztor Sep 15 '17 at 18:13
  • I want to instantiate an AmazingView() and then later set the data property of any type. But at the time of instantiating AmazingView I want to avoid declaring any type – Alexei Sep 15 '17 at 18:33
  • If I understand what you're asking, no, you can't do this. See [1](https://stackoverflow.com/questions/39469388/swift-generalized-existentials), [2](https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md) – Kevin Sep 15 '17 at 20:11

0 Answers0