gpt4 book ai didi

swift - 无法强制转换为 init 的协议(protocol)一致性

转载 作者:行者123 更新时间:2023-11-30 11:35:39 24 4
gpt4 key购买 nike

在函数内转换泛型,以符合具有 init 函数的 SomeProtocol。这不可能吗?

public func doSomething<Entity>(foo: Entity) throws -> Entity {

let aValue = someVariableSomewhere.performFunction()

// stuff happens

_ = (Entity.self as! SomeProtocol)(record: aValue) //fails

// stuff happens

// returns something
}

“SomeProtocol”具有功能

init(record: String)

最佳答案

您可以按如下方式转换为初始化协议(protocol),

let object = type(of: foo as! SomeProtocol).init(record: "stringValue")

关于swift - 无法强制转换为 init 的协议(protocol)一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49812850/

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