问题描述
我在中有以下
:协议
:Swift
I have the following protocol
in Swift
:
protocol FooConvertible{
typealias FooType
init(foo: FooType)
}
我可以使 Swift
类符合类定义:
I can make Swift
classes conform to it in the class definition:
class Bar: FooConvertible {
var baz: String = ""
required init(foo: String){
baz = foo
}
}
但是,当我试图使一个类符合它在一个扩展(使用Cocoa类,它是我唯一的选择,因为我没有源),问题出现:
So far so good. However, the problem arises when I try to make a class conform to it in an extension (With Cocoa classes, it's my only option, as I don't have the source):
class Baz {
var baz = ""
}
extension Baz: FooConvertible{
required convenience init(foo: String) { // Insists that this should be in the class definition
baz = foo
}
}
extension NSURL: FooConvertible{
required convenience init(foo: String) { // this also fails for the same reason
}
}
这
这是因为它被删除的原因是什么?
What's the reason it was removed?
意味着所有XXXLiteralConvertible协议被禁止Cocoa类!
That would mean that all the XXXLiteralConvertible Protocols are banned from Cocoa classes!
推荐答案
您尝试创建此类内容的任何机会:
Any chance you are trying to create something like this:
protocol FooConvertible : class {
typealias FooType
var baz : String { get set } // protocol extensions inits may need to know this
init(foo: FooType) // this is your designated initializer
}
extension FooConvertible {
// init(foo: String) {
// self.init(foo: foo)
// baz = foo
// }
// you can't do this because it could call it self recursively
init(num: Int) { // this init will call your designated init and can instantiate correctly
self.init(foo: "\(num)")
}
}
class Baz {
var baz = ""
}
class Bar: FooConvertible {
var baz: String = ""
required init(foo: String) { // designated initializer
baz = foo
}
}
现在将了解
FooConvertible / code>。
如果是这样,我很高兴我可以帮助。 :)
Baz
will now know about all inits of FooConvertible
.If so, I'm glad I could help. :)
这篇关于使Swift类符合需要init的协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!