Эти протоколы дают мне кошмары.Swift, классы по расширенному протоколу не соответствуют оригинальному протоколу
Я пытаюсь реализовать пару протоколов и классов, соответствующих им, так что я могу иметь реализации по умолчанию, но настраиваемые реализации доступны путем расширения протоколов/классов. До сих пор, это то, что у меня есть:
protocol ProtA {
var aProperty: String { get set }
var anotherProperty:String { get set }
func aFunc (anArgument: String) -> String
}
protocol ProtB: ProtA {
var aThirdProperty: String { get set }
}
protocol ProtC {
func doSomething(parameter: Int, with anotherParameter: ProtA)
}
class ClassA: ProtA {
var aProperty: String = "Hello, I'm a String."
var anotherProperty: String = "I'm not the same String."
func aFunc (anArgument: String) -> String {
return anArgument
}
}
class ClassB: ProtB {
var aProperty: String = "Hello, I'm a String."
var anotherProperty: String = "I'm not the same String."
var aThirdProperty: String = "I'm yet another String!"
func aFunc (anArgument: String) -> String {
return anArgument
}
}
class ClassC: ProtC {
func doSomething(parameter: Int, with anotherParameter: ProtA) {
print (anotherParameter.aProperty) // Works fine.
}
}
Тогда, если я
class ClassC: ProtC {
func doSomething(parameter: Int, with anotherParameter: ProtA) {
print (anotherParameter.aProperty) // Works fine.
}
}
Но, если я
class ClassD: ProtC {
func doSomething(parameter: Int, with anotherParameter: ProtA) {
print (anotherParameter.aThirdProperty) // Value of type 'ProtA' has no member 'aThirdProperty'
}
}
и, если вместо этого я
class ClassE: ProtC {
func doSomething(parameter: Int, with anotherParameter: ProtB) {
print (anotherParameter.aThirdProperty) // Type 'ClassE' does not conform to protocol 'ProtC'
}
}
Что я делаю неправильно?
Ну 'ProtA' не требует' aThirdProperty' - 'ProtB' делает. Вы не можете соответствовать 'ProtC' методом' func doSomething (параметр: Int, with anotherParameter: ProtB) ', поскольку' anotherParameter' должен иметь тип 'ProtA', как требует протокол. – Hamish