Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了数组 – Swift Array.insert泛型大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

func geTindex<T: Equatable>(valueToFind: T) -> Int? {...} mutaTing func replaceObjectWithObject<T: Equatable>(obj1: T, obj2: T) { if let index = self.geTindex(obj1) { self.removeATindex(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

大佬总结

以上是大佬教程为你收集整理的数组 – Swift Array.insert泛型全部内容,希望文章能够帮你解决数组 – Swift Array.insert泛型所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。