1

I came with with this simple playground illustrating my problem:

import UIKit

protocol MyProtocol {
    var foo: Bool { get set }
}

class MyGenericClass<T: UIView where T: MyProtocol>: UIView {}

func checkIfIsMyGenericClass(view: UIView) -> Bool {
    return view is MyGenericClass // Generic parameter 'T' could not be inferred
}

I need help to identify instances of MyGenericClass.

My actual code isn't that simple, please don't ask me to change MyGenericClass declaration.

gfpacheco
  • 2,831
  • 2
  • 33
  • 50
  • Possible duplicate of [Checking if an object is a given type in Swift](http://stackoverflow.com/questions/24091882/checking-if-an-object-is-a-given-type-in-swift) – Rana Apr 19 '16 at 18:33
  • Why do you need to do this? Can you not check against a particular T? – jtbandes Apr 19 '16 at 18:37
  • @jtbandes I can't because I wanna check against any `T` that extends `UIView` and conforms to `MyProtocol` – gfpacheco Apr 19 '16 at 19:10

1 Answers1

0

MyGenericClass has an associatedType requirements. I am not sure but could you try something like

import UIKit

protocol MyProtocol {
    var foo: Bool { get set }
}

class MyGenericClass<T: UIView where T: MyProtocol>: UIView {}

func checkIfIsMyGenericClass<T: UIView where T: MyProtocol>(view: T) -> Bool {
    return view is MyGenericClass<T> // Generic parameter 'T' could not be inferred
}

UPDATED

import UIKit

protocol MyProtocol {
    var foo: Bool { get set }
}

class View: UIView, MyProtocol {
    var foo: Bool = true
}

class MyGenericClass<T: UIView where T: MyProtocol>: UIView {

    var variable: T!

    init() {
        super.init(frame: CGRectZero)
    }

}

let view = View()
let obj = MyGenericClass<View>()
obj.variable = view
let anyOtherObj = UIView()


func checkIfIsMyGenericClass<T: UIView where T: MyProtocol>(view: UIView, type: T) -> Bool {
    return view is MyGenericClass<T>
}

checkIfIsMyGenericClass(obj, type: view) // returns true
checkIfIsMyGenericClass(anyOtherObj, type: view) // returns false
Rahul Katariya
  • 3,528
  • 3
  • 19
  • 24
  • I can't because my parameter `view` isn't the one that extends `UIView` and implements `MyProtocol`, but it is an instance of `MyGenericClass` that has that generic type – gfpacheco Apr 19 '16 at 19:13