Ich definiere ein Protokoll MessageProtocol
, und Klasse MessageA
, MessageB
verabschieden das Protokoll.Swift Schließung Typ Umwandlung
Ich möchte Konvertierungen wie (MessageA) -> Void
zu (MessageProtocol) -> Void
.
Es gibt Code, Lösung 1 und kann nicht gut funktionieren.
protocol MessageProtocol {
func doSomething()
static func parserFromData() -> MessageProtocol
}
class MessageA: MessageProtocol {
func doSomething() {
print("this is A class")
}
func functionInA() {
print("funciton in A")
}
static func parserFromData() -> MessageProtocol {
return MessageA()
}
}
class MessageB: MessageProtocol {
func doSomething() {
print("this is B class")
}
func functionInB() {
print("funciton in b")
}
static func parserFromData() -> MessageProtocol {
return MessageB()
}
}
// private function .network callback
func callback(type: MessageProtocol.Type, handler: (MessageProtocol?) -> Void) -> Void {
let obj = type.parserFromData()
handler(obj)
}
// public function
func response<T: MessageProtocol>(type: T.Type, handler: (T?) -> Void) -> Void {
// solution 1. compile error
// let handler: (ABProtocol) -> Void = handler // compile error
// callback(type, handler: handler)
// solution 2. runtime error
// let handler = handler as! (ABProtocol) -> Void // runtime error
// callback(type, handler: handler)
// solution 3. now i use
callback(type) { obj in
handler(obj as? T)
}
}
response(MessageA.self) { a in
guard let a = a else {
return
}
a.doSomething()
a.functionInA()
}
response(MessageB.self) { b in
guard let b = b else {
return
}
b.doSomething()
b.functionInB()
}
Ich bin verwirrt, was Sie eigentlich versuchen, und warum die Arbeitslösung nicht für Sie arbeitet. Scheint so, als ob dies ein XY-Problem sein könnte, basierend auf der vollkommenen Non-Straight-Fowardness des Problems. – nhgrif
meine Frage ist 'MessageA' kann als' MessageProtocol' konvergieren, aber warum conver '(MessageA) -> Void' als' (MessageProtocol) -> Void' wird fehlschlagen. – langyanduan