swift - 为什么我需要强制将属性强制转换为与该属性具有相同签名的通用方法?
问题描述
这是我的代码:
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 不同意我的看法。
解决方案
使您的静态方法也通用,并为从UITableViewCell
. 然后在方法参数中使用这个泛型参数
class OtherClass {
static func handle<T: UITableViewCell>(property: GenericClass<T>.SomeEnum) {}
}
推荐阅读
- azure-active-directory - az account get-access-token - 无法在用户的上下文中获取令牌
- reactjs - Ref 元素返回 null
- arrays - 谷歌查询返回每个类别的前 N 个结果
- c++ - 我有一个关于 C++ 中动态分配内存的问题
- javascript - 如何在 SAPUI5 中将日期时间字符串转换为日期?
- c# - 为什么“mouse_event”不适用于“Control.MouseButtons == MouseButtons.Left”?
- activemq-artemis - Apache Artemis:了解最大磁盘使用率并解决完整策略
- clearcase - 有没有办法通过命令行在 clearcase 上添加动态视图快捷方式?
- c# - C#中的字典
- firebase - Firestore 中如何仅显示属于特定 uid 的文档?