【问题标题】:How to check/cast class to generic type with where in Swift如何在 Swift 中使用 where 将类检查/转换为泛型类型
【发布时间】:2016-08-12 02:44:44
【问题描述】:

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

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

【问题讨论】:

标签: swift generics casting


【解决方案1】:

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

【讨论】:

  • 我不能,因为我的参数view 不是扩展UIView 并实现MyProtocol 的参数,但它是具有该泛型类型的MyGenericClass 的一个实例跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多