C where C: SomeProtocol { -6ren">
gpt4 book ai didi

Swift (4) - 泛型函数能否专门针对其 init() 生成 "empty"对象的类型?

转载 作者:可可西里 更新时间:2023-11-01 02:02:04 25 4
gpt4 key购买 nike

是否可以将泛型函数限制为仅 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 - 例如,RangeReplaceableCollectionSetAlgebra 都有产生空的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com