简体   繁体   English

无法在 swift 中使用 associatedType 作为方法 returnType,因为编译器抛出“关联类型的模糊推断”

[英]Unable to use associatedType as method returnType in swift as compiler throws “Ambiguous inference of associated type”

Was playing with associatedType.正在玩关联类型。 Compiler is not recognising the return type of the method when using associatedType.使用 associatedType 时,编译器无法识别方法的返回类型。

Here is the code sample,这是代码示例,

protocol DummyOffice {
}

struct EmptyOffice: DummyOffice {
}

protocol  Office {
    associatedtype SubBranch: DummyOffice
    var subBranch: SubBranch { get }
    func getSubBranch() -> SubBranch
}

struct Apple: Office {
    let emptyOffice = EmptyOffice()
    func getSubBranch() -> some DummyOffice {
        return EmptyOffice()
    }
    
    var subBranch: some DummyOffice {
        return EmptyOffice()
    }
}

and compiler throws this error.并且编译器会抛出此错误。

在此处输入图像描述

Questions:问题:

(1) Error is not occurring for the property "subBranch". (1) 属性“subBranch”没有发生错误。 Thats is if I didn't create a method that returns associatedType in the protocol, everything works smooth.也就是说,如果我没有在协议中创建一个返回 associatedType 的方法,那么一切都会顺利进行。

Using an opaque return type (ie some ) is not required for what you want to do.对于您想要做的事情,不需要使用不透明的返回类型(即some )。 When you go to implement the Office protocol, just return the actual type from the function and computed property you specified and the compiler will infer the associatedtype for you:当您 go 实现Office协议时,只需从 function 和您指定的计算属性返回实际类型,编译器将为您推断associatedtype类型:

protocol DummyOffice {}

struct EmptyOffice: DummyOffice {}

protocol Office {
    associatedtype SubBranch: DummyOffice
    var subBranch: SubBranch { get }
    func getSubBranch() -> SubBranch
}

struct Apple: Office {
    let emptyOffice = EmptyOffice()
    func getSubBranch() -> EmptyOffice {
        return EmptyOffice()
    }
    
    var subBranch: EmptyOffice {
        return EmptyOffice()
    }
}

As @zaitsman suggested, replacing associatedTypes with typealias is working good.正如@zaitsman 建议的那样,用 typealias 替换 associatedTypes 效果很好。

But typealias cannot be used as psuedo generic constraint, 但是 typealias 不能用作伪泛型约束,

protocol DummyOffice {
}

struct EmptyOffice: DummyOffice {
}

protocol  Office {
    typealias SubBranch =  DummyOffice
    var subBranch: SubBranch { get }
    func getSubBranch() -> SubBranch
}

struct Apple: Office {
    var subBranch: Self.SubBranch
    
    func getSubBranch() -> Self.SubBranch {
        return EmptyOffice()
    }
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM