加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – Swift Array.insert泛型

发布时间:2020-12-14 02:24:51 所属栏目:百科 来源:网络整理
导读:func getIndexT: Equatable(valueToFind: T) - Int? {...}mutating func replaceObjectWithObjectT: Equatable(obj1: T,obj2: T) { if let index = self.getIndex(obj1) { self.removeAtIndex(index) self.insert(obj2,atIndex: index) // Error here: 'T' i
func getIndex<T: Equatable>(valueToFind: T) -> Int? {...}

mutating func replaceObjectWithObject<T: Equatable>(obj1: T,obj2: T) {
    if let index = self.getIndex(obj1) {
        self.removeAtIndex(index)
        self.insert(obj2,atIndex: index)           // Error here: 'T' is not convertible to 'T'
    }
}

我有这个函数,假设用另一个元素替换元素.但我对Generics不是很熟悉,也不知道为什么这不起作用.请帮忙.

如果我从变异函数中删除Equatable,则错误消息会跳转到该func中的第一行,如果我将其替换为func find(),则会给出与第3行相同的错误.

实际上,这不可能通过Swift中现有的协议和泛型系统下的扩展来实现 – 您不能为类型的泛型子类型添加其他约束,因此您无法使用要求其内容符合的方法扩展Array等于.

您可以使用内置的Array类型看到这个限制 – 没有myArray.find(element)方法,但是有一个全局函数find()接受一个集合和一个元素,带有一个泛型约束,即集合的元素是Equatable:

func find<C : CollectionType where C.Generator.Element : Equatable>(domain: C,value: C.Generator.Element) -> C.Index?

您可以为您的方法执行此操作 – 您只需编写类似的顶级函数:

func replaceObjectWithObject<C : RangeReplaceableCollectionType where C.Generator.Element : Equatable>(inout collection: C,obj1: C.Generator.Element,obj2: C.Generator.Element) {
    if let index = find(collection,obj1) {
        removeAtIndex(&collection,index)
        insert(&collection,obj2,atIndex: index)
    }
}

var myArray = [1,2,3,4,5]
replaceObjectWithObject(&myArray,7)
// 1,7,5

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读