swift - 如何使用 Swift 中的 where 检查/将类转换为泛型类型

标签 swift generics casting

我用这个简单的 Playground 来说明我的问题:

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 声明。

最佳答案

MyGenericClass 有一个关联的类型要求。我不确定,但你能试试

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

关于swift - 如何使用 Swift 中的 where 检查/将类转换为泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36726564/

相关文章:

swift - 如何从 SCNNode 父节点中删除或删除子节点?

swift - macOS WKWebView 背景透明度

java - 如何检查在迭代器中强制转换为 T 是否安全?

java - 这个java程序有错误吗?

C# 无法将 T 转换为 T

java - 转换为泛型类的泛型子类型

Swift 变通使 `AnyObject.Type` 符合 `Equatable` ?

c# - 使用泛型类型 System.Collections.Generic.List<T> 需要 1 个类型参数

java - 如何将通用类型的类对象转换为该类型的特定实例

ios - 将表情符号编码为字符串