[英]Swift Protocol Conformance
Here is an example of a set of value relationships that I am toying around with. 这是我正在处理的一组价值关系的示例。
protocol Configurable {
func configure(data: Any?) -> Void
}
class RelatedObject {
var x: String = ""
var y: String = ""
}
class Example {
var a: String = ""
var b: String = ""
var c: String = ""
}
extension Example: Configurable {
func configure(data: Any?) //I want the parameter to be of type RelatedObject?, not Any?
{
if let d = data as? RelatedObject { //I don't want to have to do this every time i implement Configurable on an object.
//do stuff
a = d.x
b = d.y
c = d.x + d.y
}
}
}
Is there a way for my classes that implement the Configurable protocol to be able to restrict the specific type of object they accept within the function signature? 我的实现可配置协议的类是否可以限制它们在函数签名中接受的对象的特定类型?
I feel like Swift would/could/should have a way avoid a situation where I have to check class types for what gets passed into my object that I want configured. 我觉得Swift可以/应该/应该有一种方法来避免出现这样的情况:我必须检查类类型以了解传递给想要配置的对象的内容。
You are looking for typealias in your protocol definition. 您正在协议定义中寻找类型别名。
protocol Configurable {
typealias InputData
func configure(data: InputData) -> Void
}
In anything that implements your protocol you set the typealias to the type you would like. 在实现协议的任何方法中,都将typealias设置为所需的类型。
class RelatedObject {
var x: String = ""
var y: String = ""
}
class Example {
var a: String = ""
var b: String = ""
var c: String = ""
}
extension Example: Configurable {
typealias InputData = RelatedObject
func configure(data: InputData) {
a = data.x
b = data.y
c = data.x + data.y
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.