作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
C where C: SomeProtocol { -6ren">
是否可以将泛型函数限制为仅 init() 生成空对象的类型?例如:
public func constructDefaultObject<C>() -> C where C: SomeProtocol {
return C()
}
没有 where
子句,这会产生错误:
error: numbers.playground:3:12: error: non-nominal type 'C' does not support explicit initialization
return C()
^~~
如果我改用 C.init()
会出现类似的错误:
error: numbers.playground:3:12: error: type 'C' has no member 'init'
return C.init()
^ ~~~~
似乎有一些协议(protocol)提供了一个无参数的 init
- 例如,RangeReplaceableCollection
和 SetAlgebra
都有产生空的 inits收藏品。但是似乎没有一个协议(protocol)包含所有集合类型的“无参数构造函数创建集合的空实例”的概念。
最佳答案
是的,这是可能的,但用处不大:
// This is a shitty protocol that doesn't do much. Don't use it.
public protocol DefaultConstructible {
init()
}
public func constructDefaultObject<C>() -> C where C: DefaultConstructible {
return C()
}
关于Swift (4) - 泛型函数能否专门针对其 init() 生成 "empty"对象的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45572183/
我是一名优秀的程序员,十分优秀!