我正在使用泛型和协议(protocol)为我的 Utils 类创建 namespace 。在这里,当我转到 [Array] 时,我遇到了一些问题。这是代码:
在namespce.swift中: 并在数组扩展中: 谁能告诉我如何修复它?
<小时/>这里我还有另一个问题,我在函数中使用了“Self”。但 T: Sequence 类型没有 "index"成员。
最佳答案
不确定您想在这里实现什么(以及它是否仍然相关),但您应该将通用限制为 RangeReplaceableCollection
(能够使用 remove(at:)
)而不是 Sequence
。
firstIndex(of:)
方法(返回第一个匹配元素的索引)可在Collection
上使用哪里Element: Equatable
.
extension JX_TypeWrapper where T: RangeReplaceableCollection, T.Element: Equatable {
mutating func remove(object: T.Element) {
if let index = SELF.firstIndex(of: object) {
SELF.remove(at: index)
}
}
}
这允许您将数组包装到 JX_TypeWrapper
中:
var array: [Int] = [1, 2, 3]
var wrapped = JX_TypeWrapper(value: array)
wrapped.remove(object: 2)
wrapped.SELF // [1, 3]
关于ios - 在 Swift 扩展方法(数组)中使用未声明的类型 'Element',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53510745/