泛型ViewController赋值错误:无法将LevelType赋值给LevelType?求助
解决泛型ViewController中类型不匹配的错误
我正尝试创建一个支持泛型的可复用ViewController,但遇到了错误:Cannot assign value of type 'LevelType' to type 'LevelType?'。
我的代码如下:
import Foundation import UIKit protocol SomeProtocol { var id: Int { get } } protocol VCProtocol: class { func showLevelScreen<LevelType>(level: LevelType) } class SomeVC<LevelType: SomeProtocol>: UIViewController, VCProtocol { typealias LevelType = LevelType var selectedLevel: LevelType? //Cannot assign value of type 'LevelType' to type 'LevelType?' func showLevelScreen<LevelType>(level: LevelType) { selectedLevel = level } }
问题根源
你遇到的问题核心在于方法里的泛型参数和类的泛型参数重名了,但它们其实是完全独立的两个类型。
你在showLevelScreen方法前额外声明了<LevelType>,这相当于在方法内部重新定义了一个全新的泛型类型,它和类本身的LevelType(那个遵守SomeProtocol的泛型)没有任何关联。所以当你尝试把方法里的level(方法级泛型)赋值给selectedLevel(类级泛型)时,编译器会判定这是两个不兼容的类型,进而抛出错误。
解决办法
方法1:移除方法的泛型声明
既然你的类已经声明了泛型LevelType并且带有SomeProtocol约束,直接在方法里使用这个类级的泛型即可,不需要再给方法单独声明泛型:
import Foundation import UIKit protocol SomeProtocol { var id: Int { get } } protocol VCProtocol: class { func showLevelScreen<LevelType>(level: LevelType) } class SomeVC<LevelType: SomeProtocol>: UIViewController, VCProtocol { typealias LevelType = LevelType var selectedLevel: LevelType? // 移除方法前的<LevelType>,直接复用类的泛型参数 func showLevelScreen(level: LevelType) { selectedLevel = level } }
这种写法完全符合原协议的要求,因为类的LevelType相当于给协议的泛型方法做了具体化实现。
方法2:将协议改为关联类型(更优雅的设计)
如果VCProtocol是专门为这类泛型ViewController设计的,更推荐把协议改成带关联类型的形式,这样类型约束会更清晰、严谨:
import Foundation import UIKit protocol SomeProtocol { var id: Int { get } } // 修改协议为带关联类型的形式 protocol VCProtocol: class { associatedtype LevelType: SomeProtocol func showLevelScreen(level: LevelType) } class SomeVC<LevelType: SomeProtocol>: UIViewController, VCProtocol { var selectedLevel: LevelType? func showLevelScreen(level: LevelType) { selectedLevel = level } }
这里可以直接删掉多余的typealias LevelType = LevelType,因为类的泛型参数已经自动满足了协议的关联类型要求,代码结构也更简洁。
内容的提问来源于stack exchange,提问作者DevB2F
相关产品推荐
相关产品推荐

