我是泛型的新手,我想将它应用到这个逻辑中。
所以我创建了一个用户类型枚举。我有一个包含此用户类型信息的 userModel 对象。
现在我的 UIViewController A 将包含一个用户对象和一个 tableView。根据用户类型,单元格的数量和单元格设计也会发生变化。
基本上我不想将整个逻辑混杂到单元格 ForRowAtIndexPath 和其他此类方法中,这就是我研究泛型的原因。
这是我的代码
enum UserType : Int {
case None = 0, Musician, Listener
}
class User {
var userType : UserType = .None
}
class A<T:User>: UIViewController {
var selectedUser: T?
}
extension A where T.userType : UserType.Musician
{
func foo() { print("Musician") }
}
这给了我一个错误
Playground 执行失败:
error: MyPlayground.playground:13:53: error: enum element 'Musician' is not a member type of 'UserType'
extension A where T.userType : UserType.Musician {
我想知道为什么会出现此错误以及我的方法是否错误。
最佳答案
要创建扩展
,您必须仅提供编译时 已知的信息。 userType
是User
的属性,因此它是运行时 信息。它不能用于创建 extension
。
但我认为您仍然可能受益于协议(protocol)和泛型。我不确定它是否适合您,但无论如何,这是可以做到的。
您可以像这样为每种类型的用户声明协议(protocol)
protocol UserProtocol {
var userType: UserType { get }
func doYourThing()
}
protocol MusicianProtocol: UserProtocol {}
protocol ListenerProtocol: UserProtocol {}
并创建 UserProtocol
的默认实现
extension UserProtocol where Self: MusicianProtocol {
var userType: UserType { return .musician }
func doYourThing() {
print("Do-di-do!")
}
}
extension UserProtocol where Self: ListenerProtocol {
var userType: UserType { return .listener }
func doYourThing() {
print("Anything except vynil is garbage!")
}
}
当然这种方式你需要为每个用户单独的类
class Musician: MusicianProtocol {}
class Listener: ListenerProtocol {}
但是通过使用 UserProtocol
func letsPlay(_ users: UserProtocol...) {
for u in users {
u.doYourThing()
}
}
let m = Musician()
let l = Listener()
letsPlay(m, l)
关于ios - 使用枚举和泛型快速扩展类的 Where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51533610/