【发布时间】:2021-09-11 22:12:25
【问题描述】:
假设我有一个协议
protocol TestProtocol {
}
另外,有一个结构并从协议继承它。
struct StructOne: TestProtocol {
}
现在,我有一个视图控制器类并创建了一个通用函数来接受TestProtocol 类型对象的数组(这是一个通用参数)。这是用于 SDK API 调用的传递参数。
但是在一些API调用中,我不需要传递这个参数数组。所以,我只想在函数定义中设置 nil 值或默认空数组。
这是课程
class TestViewController: UIViewController {
// func genericCall<T: TestProtocol>(param: [T] = []) { // Not work
// func genericCall<T: TestProtocol>(param: [T]? = nil) { // Not work
func genericCall<T: TestProtocol>(param: [T]?) {
if param?.isEmpty == true {
print("Empty Param Calling")
} else {
print("With Param Calling")
}
}
override func viewDidLoad() {
super.viewDidLoad()
let param = [StructOne(), StructOne()]
self.genericCall(param: param) // This one work
self.genericCall(param: [] as [StructOne]) // This one also work. But want default value in function
self.genericCall(param: nil) // Not work : Error - Generic parameter 'T' could not be inferred
// self.genericCall() // Not work with default empty value : Error - Generic parameter 'T' could not be inferred
}
}
我收到此编译时错误:无法推断通用参数“T”
我可以在函数调用期间设置一个空数组。这是提到here
我还检查了这个link,如果只有 T 类型,它允许设置 nil 值,但这里是 T ([T]) 的数组。
有没有办法设置默认的 nil 值或任何其他方式来设置默认的空数组?这样我们就可以避免向每个函数调用传递一个空数组。
更新:
我不能这样使用它。由于 SDK 函数调用不允许我传递参数值。
func genericCall(param: [TestProtocol] = []) {
// param: Not allowed me to pass to the sdk call function.
if param.isEmpty == true {
print("Empty Param Calling")
} else {
print("With Param Calling")
}
}
注意:这是一个演示代码。实际上,我正在使用其中一个 SDK,所以我无法在协议中进行更多更改。
【问题讨论】:
-
你为什么在这里使用泛型?为什么不直接声明
func genericCall(param:[TestProtocol]?) -
如果您确实需要泛型(即,这只是问题的一个简单示例),但是泛型类中的泛型函数,然后您可以创建该类的专用实例并
T不需要推断 -
@Paulw11 我使用了你的方法,这是我的第一次尝试,但是当我将此参数值传递给 SDK 函数时,调用它会抛出错误
Protocol as a type cannot conform to the protocol itself
标签: ios swift generics protocols