gpt4 book ai didi

Swift 扩展和 'Element' 显式初始化

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

我想知道是否有任何其他方法可以显式初始化 Swift 扩展中的 Element 对象?

例如,我想这样做,但非标称类型“Element”不支持显式初始化

extension Array where Element: Numeric {
func findDuplicate() -> Int {
guard self.count > 0 else { return -1 }
let sum = self.reduce(0, +)
let expectedSum = Element((self.count - 1) * self.count / 2)
return sum - expectedSum
}
}

当然,如果我删除 expectedSum 赋值中的强制 Element 转换并让编译器使用 Int,我会在比较 sum (Element) 和 expectedSum (Int) 时得到一个错误

我可以很容易地让我的扩展与 where Element == Int 一起工作,但当然这不再是通用的。

有什么提示吗?

最佳答案

整数到Numeric 类型的转换是用init?(exactly:) 完成的.考虑 Leo 的建议:

extension Array where Element: Numeric {
func findDuplicate() -> Element? {
guard !isEmpty else { return nil }
let sum = self.reduce(0, +)
guard let expectedSum = Element(exactly: (count - 1) * count / 2) else { return nil }
return sum - expectedSum
}
}

另一方面,这似乎是一项编程任务特别是关于整数,然后它可能更有意义将元素类型限制为 BinaryInteger(并使用 Int用于避免溢出的中间计算):

extension Array where Element: BinaryInteger {
func findDuplicate() -> Element? {
guard !isEmpty else { return nil }
let sum = Int(reduce(0, +))
let expectedSum = (count - 1) * count / 2
return Element(sum - expectedSum)
}
}

甚至 Element == Int

关于Swift 扩展和 'Element' 显式初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043001/

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