【问题标题】:Swift Extension and 'Element' explicit initializationSwift 扩展和“元素”显式初始化
【发布时间】:2017-10-31 19:14:22
【问题描述】:

我想知道是否有任何其他方法可以在 Swift 扩展中显式初始化 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 一起工作,但当然这不再是通用的了。

有什么提示吗?

【问题讨论】:

  • 首先不要使用count属性来检查你的数组是否为空。其次,使返回类型可选而不是返回-1。顺便说一句,您的方法应该做什么?
  • 如果您返回 Int.返回Element? 并使用BinaryIntegerFloatingPoint 而不是Numeric
  • 上面的算法是如何实现“查找重复”的,还不是很清楚。返回值的含义是什么?为什么它是一个整数(“重复”是怎么回事)?在这种情况下,“显式初始化”是什么意思? Numeric 包括用于从任何BinaryInteger 转换的init?(exactly:)(并且count 始终为Int,因此适用)。但很不清楚你的意思是这段代码做什么。
  • @RobNapier:可能是这样的任务“你有一个从1到n-1的n个数字的数组,其中恰好一个数字出现了两次。找到重复的元素。

标签: swift extension-methods


【解决方案1】:

整数到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

【讨论】:

  • 谢谢 MartinR,Element(exactly: ) 正是我想要的。顺便说一句,我同意上面的任何 cmets,“在 n 个数字 + 1 的数组中查找重复项”代码只是解释我的问题的一种快速方法。 @LeoDabus 该方法仅适用于您有一个由 1...n 值和一个副本组成的随机有序数组的特定场景。再一次,这只是一个简单的例子来解释在扩展中元素显式初始化的用法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
  • 2012-11-13
  • 1970-01-01
  • 2014-01-03
相关资源
最近更新 更多