gpt4 book ai didi

Swift 类型删除尝试 : "Reference to invalid associated type"

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:56 24 4
gpt4 key购买 nike

我正在做一个伪造的练习来尝试实现类型删除的容器。

import Foundation

protocol MoverType {
func move()
}
extension MoverType {
func move() { print("\(type(of: self)) is moving") }
}

class Slithering: MoverType {}
class Walking: MoverType {}
class Trotting: MoverType {}

protocol Animal {
associatedtype Mover: MoverType
var mover: Mover { get }
}

class Snake: Animal {
let mover = Slithering()
}
class Dog: Animal {
let mover = Trotting()
}
class Human: Animal {
let mover = Walking()
}

class AnyAnimal: Animal { // ERROR: Type 'AnyAnimal' does not conform to protocol 'Animal'
var _mover: () -> Mover
init<A: Animal>(animal: A) where Mover == A.Mover {
_mover = {
return animal.mover
}
}

// ERROR HERE: "Reference to invalid associated type "Mover" of of type "AnyAnimal"
var mover: Mover { fatalError() }
}

let d = AnyAnimal(animal: Dog())
let s = AnyAnimal(animal: Snake())

let animals = [d, s] // Array<AnyAnimal>
for a in animals {
a.mover.move()
}

我故意不想要我的 AnyAnimal容器是一个AnyAnimal<T>容器。因为,我希望能够存储很多 Animal Array<AnyAnimal> 中的实例.

但是,正如您在上面的代码中看到的,编译器提示 AnyAnimal类(class)。据我了解 Mover 的协议(protocol)要求将由通用 where 解决AnyAnimal 中的条款初始化程序。

请帮助我了解缺少的内容。 (或者,甚至有可能首先创建一个非通用类型删除包装器吗?)

最佳答案

您的代码无法编译,因为需要在编译时通过为 Mover 协议(protocol)提供具体实现来解析关联类型。

您可以做的是同时删除 MoverType 协议(protocol):

struct AnyMover: MoverType {
private let mover: MoverType

init(_ mover: MoverType) {
self.mover = mover
}

func move() {
mover.move()
}
}

class AnyAnimal: Animal {
let mover: AnyMover

init<A: Animal>(animal: A) {
mover = AnyMover(animal.mover)
}
}

关于Swift 类型删除尝试 : "Reference to invalid associated type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58124668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com