我有一个功能:
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
}
我打电话的时候:
let vc = ShowUserInfoVC.create(userId: id, streamId: id)
它说错误:
无法推断通用参数“T”
答案 0 :(得分:4)
当你调用一个函数时,swift编译器必须能够推断出每个泛型参数。
如果传递nil
,则无法推断泛型参数,因为它与每个可选类型兼容。
您必须告诉它nil
属于某种类型。您可以通过强制转换来执行此操作:
let vc = ShowUserInfoVC.create(userId: id, streamId: id, delegateToController: nil as SomeType?)
正如亚历山大在评论中所建议的那样,SomeType?.none
和Optional<SomeType>.none
同样适用
其中SomeType
是满足约束条件的类型。
那很糟糕,不是吗?
解决方法是创建create
的重载,只需要3个参数,并且如上所示调用create
。
例如:
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
}