如何检查/将类转换为泛型类型与Swift中的位置

时间:2016-04-19 18:26:59

标签: swift generics casting

我带着这个简单的游乐场来说明我的问题:

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
}

我需要帮助来识别MyGenericClass

的实例

我的实际代码并不那么简单,请不要让我更改MyGenericClass声明。

1 个答案:

答案 0 :(得分:0)

MyGenericClass具有associatedType要求。我不确定,但你可以试试像

这样的东西
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
}

<强>已更新

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