I have a function :
static func create<T>(userId: Int, streamId: Int, isPushStream: Bool = false, delegateToController controller: T? = nil) -> ShowUserInfoVC where T: UIViewController, T: ShowUserInfoVCDelegate {
let showUserInfoVC = ShowUserInfoVC()
showUserInfoVC.modalTransitionStyle = .crossDissolve
showUserInfoVC.modalPresentationStyle = .overCurrentContext
showUserInfoVC.delegate = controller
showUserInfoVC.userId = userId
showUserInfoVC.streamId = streamId
showUserInfoVC.isPushStream = isPushStream
return showUserInfoVC
}
When I call:
let vc = ShowUserInfoVC.create(userId: id, streamId: id)
It says error:
Generic parameter 'T' could not be inferred
When you call a function, the swift compiler must be able to infer every generic parameter.
If you pass nil, the generic parameter cannot be inferred, because it is compatible with every optional type.
You must tell it that this nil is of a certain type. You can do this by casting:
let vc = ShowUserInfoVC.create(userId: id, streamId: id, delegateToController: nil as SomeType?)
As Alexander in the comments suggested, SomeType?.none and Optional<SomeType>.none work as well
where SomeType is a type that satisfies the constraints.
That sucks, doesn't it?
A workaround for this is to create an overload of create that takes only 3 arguments, and have that call create as shown above.
For example:
static func create<T>(userId: Int, streamId: Int, isPushStream: Bool = false) -> ShowUserInfoVC where T: UIViewController, T: ShowUserInfoVCDelegate {
create(userId: userId, streamId: streamId, isPushStream: isPushStream, delegateToController: nil as DummyController?)
}
// private/fileprivate "dummy" class
private class DummyController: UIViewController, ShowUserInfoVCDelegate {
// implement methods with stubs
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With