ios - 在 Swift 扩展方法(数组)中使用未声明的类型 'Element'

标签 ios swift generics namespaces protocols

我正在使用泛型和协议(protocol)为我的 Utils 类创建 namespace 。在这里,当我转到 [Array] 时,我遇到了一些问题。这是代码:

在namespce.swift中: enter image description here 并在数组扩展中: enter image description here 谁能告诉我如何修复它?

<小时/>

更新: 我将代码更改为: enter image description here

这里我还有另一个问题,我在函数中使用了“Self”。但 T: Sequence 类型没有 "index"成员。

最佳答案

不确定您想在这里实现什么(以及它是否仍然相关),但您应该将通用限制为 RangeReplaceableCollection (能够使用 remove(at:) )而不是 SequencefirstIndex(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/

相关文章:

ios - 获取 html 代码并编辑然后加载到 web View

iphone - Itunes Connect 的问题和需要澄清

IOS app Performance is too slow for parse data with swiftyjson

c# - C# 和 Java 中的泛型与 C++ 中的模板有什么区别?

java - 对以前未知元素的列表进行排序 (List<?>)

ios - 在自定义 UITableViewCell 中调整 UITextView 的大小

ios - 如何从 UITableView 中的 Web 服务加载大量数据?

swift - 由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序。无法识别的选择器发送到实例

ios - UIView 在没有 UIViewController 的情况下获取宽度/高度

Java 泛型 <?> 的含义