Swift:返回运行时随机不透明类型会产生错误

Swift: returning a runtime random opaque type generates an error

我现在正在学习不透明类型,仍然有点困惑。我尝试了以下方法:

protocol Animal {
    func introduce()
}

struct Dog: Animal {
    func introduce() {
        print("Dog")
    }
}

struct Cat: Animal {
    func introduce() {
        print("Cat")
    }
}

func random() -> some Animal {
    let value = [true, false].randomElement()!
    return value ? Cat() : Dog()
}

并且在 random 的 return 行中出现以下错误

Result values in '? :' expression have mismatching types 'Cat' and 'Dog'

因此,据我所知,就像泛型一样,编译器需要能够在编译时决定函数的具体 return 类型是什么。

我说的对吗?如果我是,这条消息不是关于混淆两个结构实现 Animal 吗?如果我错了,这条错误消息是什么意思?

非常感谢

编辑:我试图理解,而不是让它发挥作用:)

考虑一下:表达式值的类型是什么?猫狗() 它不是动物。对于三元组,您需要一种类型,但您有一只猫或一只狗。类型推断不会弄清楚你可以将这两种不同的类型擦除回一些常见的类型,即使这样做是可能的