gpt4 book ai didi

由方法上下文定义的 Swift 泛型类型

转载 作者:行者123 更新时间:2023-11-28 12:33:43 24 4
gpt4 key购买 nike

是否有一种模式的名称,其中类型是根据结果类型的上下文推断的?

例如,在这个例子中,我可以使用什么语言来记录 foo 方法并解释需要为该方法定义一个类型?

protocol FooType {
init()
}

func foo<T: FooType>() -> T {
return T()
}

struct Bar: FooType {
init() {
print("bar")
}
}


let bar: Bar = foo()
// works returns instance of Bar

let fooType = foo()
// fails because foo doesn't know what type to use

最佳答案

你不需要记录这个!

用 Swift 写代码的人都知道,要调用一个泛型函数,它的所有类型参数都必须被推断出来,不能像这样被填满:

foo<Bar>()

人们会看到 foo 并说,“哦,我需要编译器推断这个泛型参数的类型。”他们会明白这意味着什么。

关于由方法上下文定义的 Swift 泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41454003/

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