首页 > 解决方案 > 为什么我需要强制将属性强制转换为与该属性具有相同签名的通用方法?

问题描述

这是我的代码:

class GenericClass<T: UITableViewCell> {

    let enumProperty = SomeEnum.myValue

    enum SomeEnum {
        case myValue
    }

    func callOtherClass() {
        OtherClass.handle(property: enumProperty) // Compile error
    }
}

class OtherClass {
    static func handle(property: GenericClass<UITableViewCell>.SomeEnum) {}
}

为什么会出现编译错误:

无法将“GenericClass.SomeEnum”类型的值转换为预期的参数类型“GenericClass.SomeEnum”

当然,解决方法是添加演员表:

as! GenericClass<UITableViewCell>.SomeEnum

这导致了这个丑陋的代码:

func callOtherClass() {
    OtherClass.handle(property: enumProperty) as! GenericClass<UITableViewCell>.SomeEnum
}

但是为什么我需要施法呢?self被定义为 GenericClass,其中T始终是UITableViewCell. 该方法handle需要该签名。

是否有任何情况需要这种演员,因为在某些情况下这会/可能会失败?我不希望 Swift 只是随机要求我插入强制转换。我希望 Swift 可以推断类型并认为它是安全的,但不知何故,Swift 不同意我的看法。

标签: swiftgenerics

解决方案


使您的静态方法也通用,并为从UITableViewCell. 然后在方法参数中使用这个泛型参数

class OtherClass {
    static func handle<T: UITableViewCell>(property: GenericClass<T>.SomeEnum) {}
}

推荐阅读