在 swift 中扩展 Set 数据类型
Extending the Set datatype in swift
我是 swift 新手。我在 Set 数据结构中为我的代码创建了一个新方法。仅当值不等于特定数字时,此方法才插入到集合中。
extension Set {
mutating func addExcludingCurrent(value: Int, currIndex: Int) {
if value == currIndex {
return
} else {
self.insert(value) // Error
}
}
}
Cannot invoke 'insert' with an argument list of type '(Int)'
。我该如何解决。或者还有更好的方法来完成这项任务吗?
A Set
是 struct
,其 AssociatedType
定义为 Element
。所以你可以通过插入元素而不是整数来扩展它:
extension Set {
mutating func addExcludingCurrent(value: Element, currIndex: Element) {
if value == currIndex {
return
} else {
self.insert(value)
}
}
}
var a = Set<Int>();
a.insert(3)
a.addExcludingCurrent(5,currIndex: 5)
试试这个:
extension Set {
mutating func addExcludingCurrent(value: Element, currIndex: SetIndex<Element>) {
if value == currIndex {
return
} else {
self.insert(value) // No more mistakes
}
}
}
在Swift中Index
定义如下:
public typealias Index = SetIndex<Element>
所以你可以这样写扩展:
extension Set {
mutating func addExcludingCurrent(value: Element, currIndex: Index) {
if value == currIndex {
return
} else {
self.insert(value) // No more mistakes
}
}
}
我是 swift 新手。我在 Set 数据结构中为我的代码创建了一个新方法。仅当值不等于特定数字时,此方法才插入到集合中。
extension Set {
mutating func addExcludingCurrent(value: Int, currIndex: Int) {
if value == currIndex {
return
} else {
self.insert(value) // Error
}
}
}
Cannot invoke 'insert' with an argument list of type '(Int)'
。我该如何解决。或者还有更好的方法来完成这项任务吗?
A Set
是 struct
,其 AssociatedType
定义为 Element
。所以你可以通过插入元素而不是整数来扩展它:
extension Set {
mutating func addExcludingCurrent(value: Element, currIndex: Element) {
if value == currIndex {
return
} else {
self.insert(value)
}
}
}
var a = Set<Int>();
a.insert(3)
a.addExcludingCurrent(5,currIndex: 5)
试试这个:
extension Set {
mutating func addExcludingCurrent(value: Element, currIndex: SetIndex<Element>) {
if value == currIndex {
return
} else {
self.insert(value) // No more mistakes
}
}
}
在Swift中Index
定义如下:
public typealias Index = SetIndex<Element>
所以你可以这样写扩展:
extension Set {
mutating func addExcludingCurrent(value: Element, currIndex: Index) {
if value == currIndex {
return
} else {
self.insert(value) // No more mistakes
}
}
}