问题描述
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'
}
}
我有一个是假设有另一个元素替换元素的功能。但我不是很熟悉的泛型
,不知道为什么,这是行不通的。请帮助。
I have that function which is suppose to replace an element with another element. But Im not very familiar with Generics
and don't know why this is not working. Please help.
如果我从突变中删除Equatable FUNC错误消息跳转到该FUNC第一线,如果我再替换使用FUNC 找到()
,让我同样的错误作为第3行。
If I remove the Equatable from the mutating func the error message jumps to the first line in that func and if I then replace that with the func find()
that gives me the same error as on line 3.
推荐答案
这实际上是不可能的通过扩展的斯威夫特协议和仿制药的现行制度下 - 你不能添加额外的约束一种类型的通用子类型,所以你不能延长阵列
与要求,其内容符合 Equatable的方法
。
This is actually not possible via an extension under the existing system of protocols and generics in Swift - you can't add additional constraints to the generic subtype of a type, so you can't extend Array
with a method that requires that its contents conform to Equatable
.
您可以看到与内置阵列式动作此限制 - 有没有 myArray.find(元素)
方法,但有是全局函数找到()
接受一个集合和一个元素,一个通用的约束集合的元素是 Equatable
:
You can see this restriction in action with the built-in Array type -- there's no myArray.find(element)
method, but there is a global function find()
that takes a collection and an element, with a generic constraint that the collection's elements are Equatable
:
func find<C : CollectionType where C.Generator.Element : Equatable>(domain: C, value: C.Generator.Element) -> C.Index?
您可以作为你的方法做到这一点 - 你只需要编写一个类似的顶级功能:
You can do this for your method - you just need to write a similar top-level function:
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, 2, 7)
// 1, 2, 7, 4, 5
这篇关于斯威夫特Array.insert仿制药的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!