Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift协议中关联类型的约束_Swift_Swift Protocols - Fatal编程技术网

Swift协议中关联类型的约束

Swift协议中关联类型的约束,swift,swift-protocols,Swift,Swift Protocols,我正在编写一个小代码片段来了解关联类型是如何工作的,但是我遇到了一个错误,我不知道如何解释。下面是我写的代码,仅供参考 // A basic protocol protocol Doable { func doSomething() -> Bool } // An extension that adds a method to arrays containing Doables extension Array where Element: Doable { func m

我正在编写一个小代码片段来了解关联类型是如何工作的,但是我遇到了一个错误,我不知道如何解释。下面是我写的代码,仅供参考

// A basic protocol
protocol Doable {
    func doSomething() -> Bool
}

// An extension that adds a method to arrays containing Doables
extension Array where Element: Doable {

    func modify(using function:(Array<Doable>)->Array<Doable>) -> Array<Doable> {
        return function(self)
    }
}

// Another protocol with an associated type constrained to be Doable
protocol MyProtocol {
    associatedtype MyType: Doable

    func doers() -> Array<MyType>

    func change(_:Array<MyType>) -> Array<MyType>
}

// An simple extension
extension MyProtocol {

    func modifyDoers() -> Array<MyType> {
        return doers().modify(using: change)
    }
}
//基本协议
协议可行{
func doSomething()->Bool
}
//向包含DOABLE的数组添加方法的扩展
扩展数组,其中元素:Doable{
func modify(使用函数:(数组)->Array)->Array{
返回函数(self)
}
}
//另一个关联类型受限为可行的协议
协议MyProtocol{
associatedtype MyType:可行
func doers()->数组
func change(quo:Array)->Array
}
//简单的扩展
扩展MyProtocol{
func modifyDoers()->数组{
return doers().modify(使用:change)
}
}

我已将
MyType
约束为
Doable
,但编译器抱怨无法将
(数组)->数组转换为预期的参数类型(数组)->数组
。有人能解释一下这里发生了什么,以及我如何让编译器满意吗?

正如错误消息所说,
modify
函数需要类型为
Array
的参数,而您正在传递类型为
Array
的参数

这个问题源于
modify
的定义,在该定义中,您在参数中明确使用
Doable
,它排除了除
Doable
之外的所有其他类型,并且由于关联的类型不是类型别名,
MyType
无法转换为
Doable


修复方法是将
modify
函数中出现的所有
Doable
更改为
Element
,如Swift文档所示:。

极好的解释。谢谢你的链接。这就是我如此爱你的原因。