有人能告诉我我的代码有什么问题吗?
protocol PersonWithName: class {
var personName: String {get set}
init(name: String)
}
class NameCard<PersonType: SKSpriteNode where PersonType: PersonWithName> {
var person: PersonType
init() {
self.person = PersonType(name: "No Name") // this line error.
}
}
答案 0 :(得分:0)
对于较短的说明,我将SKSpriteNode
替换为Any
,因为您必须稍后更详细地处理指定的init()
SKSpriteNode
..有关初始化程序要求的详细信息在协议中,请查看this section of Apple's Developer Guide
protocol PersonWithName: class {
var personName: String {get set}
init(name: String)
}
class NameCard<PersonType: Any where PersonType: PersonWithName> {
var person: PersonType
init() {
self.person = PersonType(name: "No Name")
}
}
class ExampleClass: PersonWithName {
var personName: String = ""
required init(name: String) {
personName = name
}
}
var test = NameCard<ExampleClass>()
print(test.person.personName) // "No Name"
答案 1 :(得分:0)
我目前的不完美解决方案。@FlorianWeßling
protocol PersonWithName: class {
var personName: String {get set}
init(name: String)
}
protocol SKSpriteNodeProtocol {
var position: CGPoint {get set}
var size: CGSize {get set}
//or more properties you want
}
class NameCard<PersonType: SKSpriteNodeProtocol where PersonType: PersonWithName> {
var person: PersonType
init() {
self.person = PersonType(name: "No Name")
}
}
extension SKSpriteNode : SKSpriteNodeProtocol {}
class ExampleClass: SKSpriteNode, PersonWithName {
var personName: String = ""
required init(name: String) {
personName = name
super.init(texture: nil, color: UIColor.clearColor(), size: CGSizeZero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
var test = NameCard<ExampleClass>()
print(test.person.personName) // "No Name"
答案 2 :(得分:0)
如果访问unpivot
中的SKSpriteNode
非常重要,那么您可以添加一个简单变量NameCard
并从node
中移除继承:
SKSpriteNode