无法在Swift中的另一个协议中使用协议作为关联类型我有一个协议,Address它继承自另一个协议Validator,并Address满足Validator扩展中的要求。还有另一个协议,FromRepresentable它有一个associatedType(ValueWrapper)要求Validator。现在,如果我尝试使用Addressas associatedType,那么它不会编译。它说,推断类型'Address'(通过匹配要求'valueForDetail')无效:不符合'Validator'。这种用法是非法的吗?我们是不是应该能够使用Address的地方Validator,因为所有Addresses都是Validator。下面是我正在尝试的一段代码。enum ValidationResult {
case Success
case Failure(String)}protocol Validator {
func validate() -> ValidationResult}//Address inherits Validatorprotocol Address: Validator {
var addressLine1: String {get set}
var city: String {get set}
var country: String {get set}}////Fulfill Validator protocol requirements in extensionextension 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 }
}}更新:提起了一个错误。
2 回答
- 2 回答
- 0 关注
- 577 浏览
添加回答
举报
0/150
提交
取消