gpt4 book ai didi

swift - 将 UInt32 转换为通用 T : Numeric

转载 作者:行者123 更新时间:2023-11-28 07:30:31 25 4
gpt4 key购买 nike

我正在编写一个通用(数字)类,需要将 Uint32 结果(来自 arc4random())转换为通用 T。T 被限制为数字。这是怎么做到的?

最佳答案

Numeric 协议(protocol)有一个 init?(exactly:)带有 BinaryInteger 参数的可失败初始化器。如果 T 符合 Numeric 那么你可以做

guard let val = T(exactly: arc4random()) else {
// Handle error ...
}

正如 Alexander 所提到的,您可能希望利用新的随机 API,例如

guard let val = T(exactly: UInt32.random(in: 0..<100)) else {
// Handle error ...
}

关于swift - 将 UInt32 转换为通用 T : Numeric,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54861599/

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