假设我有一个协议(protocol)
protocol TestProtocol {
}
此外,有一个结构体并从协议(protocol)继承它。
struct StructOne: TestProtocol {
}
现在,我有一个 View Controller 类并创建了一个通用函数来接受一组 TestProtocol
类型对象(这是一个通用参数)。这是用于SDK API调用的传递参数。
但是在一些API调用中,我不需要传递这个参数数组。所以,我只想在函数定义中设置 nil 值或默认空数组。
这是类(class)
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,因此我无法在协议(protocol)中进行更多更改。
最佳答案
nil
在这种情况下太宽泛,因为编译器无法推断应该将 nil 应用到哪个 [T]?
。
您需要在此处显式指定可选
通用参数:
self.genericCall(param: [StructOne]?.none)
关于ios - 将默认值或 nil 值设置为函数的泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68183125/