Protokoll kann in Swift @ nicht als assoziierter Typ in einem anderen Protokoll verwendet werd
Ich habe ein Protokoll,Address
, das von einem anderen Protokoll erbt,Validator
, undAddress
erfüllt dasValidator
Anforderung in der Erweiterung.
Es gibt ein anderes Protokoll,FromRepresentable
, das ein @ hassociatedType
(ValueWrapper
) Anforderung, die @ sein soValidator
.
Now, wenn ich versuche, @ zu verwendAddress
wieassociatedType
, dann kompiliert es nicht. Es sagt
Der abgeleitete Typ "Adresse" (bei Übereinstimmung mit der Anforderung "valueForDetail") ist ungültig: entspricht nicht dem "Validator".
Ist diese Verwendung illegal? Sollten wir nicht in der Lage sein, @ zu verwendAddress
anstelle vonValidator
, wie alleAddresses
sindValidator
.
Below ist der Code, den ich versuche.
enum ValidationResult {
case Success
case Failure(String)
}
protocol Validator {
func validate() -> ValidationResult
}
//Address inherits Validator
protocol Address: Validator {
var addressLine1: String {get set}
var city: String {get set}
var country: String {get set}
}
////Fulfill Validator protocol requirements in extension
extension Address {
func validate() -> ValidationResult {
if addressLine1.isEmpty {
return .Failure("Address can not be empty")
}
return .Success
}
}
protocol FormRepresentable {
associatedtype ValueWrapper: Validator
func valueForDetail(valueWrapper: ValueWrapper) -> String
}
// Shipping Address conforming to Address protocol.
// It should also implicitly conform to Validator since
// Address inherits from Validator?
struct ShippingAddress: Address {
var addressLine1 = "CA"
var city = "HYD"
var country = "India"
}
// While compiling, it says:
// Inferred type 'Address' (by matching requirement 'valueForDetail') is invalid: does not conform
// to 'Validator'.
// But Address confroms to Validator.
enum AddressFrom: Int, FormRepresentable {
case Address1
case City
case Country
func valueForDetail(valueWrapper: Address) -> String {
switch self {
case .Address1:
return valueWrapper.addressLine1
case .City:
return valueWrapper.city
case .Country:
return valueWrapper.country
}
}
}
Aktualisieren Abgelegt einFehler