[英]Passing nil to a function with an optional generically constrained parameter in a protocol extension
I have a situation where I declare two functions in a protocol, one of them takes an optional generically constrained parameter, the other function takes no parameters, but needs to be implemented in an extension as a default function where it calls the one with a parameter and passes nil
. 我遇到的情况是,我在协议中声明了两个函数,其中一个带有一个可选的通用约束参数,另一个函数没有任何参数,但是需要在扩展中实现为默认函数,在默认函数中它使用参数来调用一个并通过
nil
。 However I get this error: 但是我得到这个错误:
Argument passed to call that takes no arguments
传递给不带参数的调用的参数
My code: 我的代码:
public protocol MenuAccessible {
var menuEntryViewController: UIViewController { get }
}
public protocol MenuTabBarControllerProtocol {
func reloadTabs<T>(from uiProvider: T?) where T: MenuAccessible
func reloadTabs()
}
public extension MenuTabBarControllerProtocol {
func reloadTabs() {
reloadTabs(from: nil) // error here, can't infer type
}
}
Obviously the compiler is not able to infer the type. 显然,编译器无法推断类型。 If I for example pass a
nil
( Optional
) of the required type, then the compiler is happy. 例如,如果我传递所需类型的
nil
( Optional
),则编译器很高兴。 For example: 例如:
struct MenuAccessibleObject: MenuAccessible {
var menuEntryViewController: UIViewController { return UIViewController() }
}
public extension MenuTabBarControllerProtocol {
func reloadTabs() {
let menuAccessible: MenuAccessibleObject? = nil
reloadTabs(from: menuAccessible) // passes nil, but compiler is happpy
}
}
Is there a way to pass nil in my default function implementation and not have to create that dummy object? 有没有办法在我的默认函数实现中传递nil而不用创建该虚拟对象?
I don't understand why you are Using Generic T
there if you are defining type is MenuAccessible
我不明白为什么您在定义Type为
MenuAccessible
情况下使用Generic T
Following is simply compiler without any issue 以下是简单的编译器,没有任何问题
public protocol MenuAccessible {
var menuEntryViewController: UIViewController { get }
}
public protocol MenuTabBarControllerProtocol {
func reloadTabs(from uiProvider: MenuAccessible?)
func reloadTabs()
}
public extension MenuTabBarControllerProtocol {
func reloadTabs() {
reloadTabs(from: nil)
}
}
public extension MenuTabBarControllerProtocol {
func reloadTabs(from uiProvider: MenuAccessible?) {
fatalError() // implement me
}
}
EDIT 编辑
I don't know this will work for you or not but try this 我不知道这对您是否有用,但是尝试一下
public protocol MenuAccessible {
var menuEntryViewController: UIViewController { get }
}
public class UIProvider:NSObject {
}
public protocol MenuTabBarControllerProtocol {
func reloadAllTheItems<T>(from uiProvider: T?) where T: UIProvider, T: MenuAccessible
func reloadTabs()
}
public extension MenuTabBarControllerProtocol {
func reloadTabs() {
self.reloadAllTheItems(from: Temp())
}
func reloadAllTheItems (provider:(UIProvider & MenuAccessible)) {
}
}
class Temp: (UIProvider & MenuAccessible) {
var menuEntryViewController: UIViewController {
return UIViewController()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.