Let's say I have one protocol
protocol TestProtocol {
}
Also, have one struct and inherited it from protocol.
struct StructOne: TestProtocol {
}
Now, I have one view controller class and created one generic function to accept an array of TestProtocol
type objects(This is a generic arugment). This is for the passing parameter for SDK API calls.
But in some API calls, I do not need to pass this parameter array. So, I just wanted to set nil value or default empty array within the function definition.
Here is the 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
}
}
I am getting this compile-time error: Generic parameter 'T' could not be inferred
I can set an empty array during the function call. which is mention here
I also check this link, which allows setting nil value if have only T type, but in here is the array of T ([T]).
Is there any way to set the default nil value or any other way to set default an empty array? so we can avoid passing an empty array to each function call.
Update:
I can't use it this way. As SDK function call not allowed me to pass param value.
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")
}
}
Note: This is a demo code. In reality, I'm using one of the SDK so, I cant change more in the protocol.