gpt4 book ai didi

swift - 相当于 Swift 中的 Java LinkedHashSet

转载 作者:可可西里 更新时间:2023-10-31 23:48:52 29 4
gpt4 key购买 nike

在java中我们有:

private Set<AutoComplete> hashList = new LinkedHashSet<>();

和:

public class AutoComplete {

private String name;
private String id;

//...geters and setters

@Override
public boolean equals(Object o) {
if (o instanceof AutoComplete) {
AutoComplete autoComplete = (AutoComplete) o;
if (name.equals(autoComplete.name) && id.equals(autoComplete.id))
return true;
}
return false;
}

@Override
public int hashCode() {
int hash = 17;
int hashMultiplikator = 79;
try {
hash = hashMultiplikator * hash
+ getId().hashCode();
} catch (java.lang.Exception e) {
e.printStackTrace();
MLogger.logException("autocomplete id can't be null", e);
}
return hash;
}

然后当您将项目添加到 hashList 时,将不允许重复值并且列表是排序的。

所以我的问题是如何在 Swift 中做到这一点?!

我已经看到了 Does there exist within Swift's API an easy way to remove duplicate elements from an array?

当我将 AutoComplete 数组传递给 func uniq 时,

var namesAndIds : [AutoComplete] = []

(用于删除重复项:)

namesAndIds.appendContentsOf(SingletonMappingContacts.sharedInstance.autoComplete)
namesAndIds = uniq(namesAndIds)

func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
var buffer = [T]()
var added = Set<T>()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}

我有这个:AutoComplete 类型的值没有成员元素

自动完成:

class AutoComplete{
var id : String
var name : String
init(id: String,name: String) {
self.name = name
self.id = id
}
}

最佳答案

对于想知道的人,我最终避免了如下所示的重复插入问题。但是这不会像 LinkedHashSet 那样排序 所以问题仍然存在!

我创造了

var namesAndIds = Set<AutoComplete>()
var finalAutoCompleteList = [AutoComplete]()

然后更正了 AutoComplete 类:

public class AutoComplete:NSObject{
var id : String
var name : String
init(id: String,name: String) {
self.name = name
self.id = id
}
override public func isEqual(object: AnyObject?) -> Bool {
if let object = object as? AutoComplete {
return id == object.id
} else {
return false
}
}

override public var hash: Int {
return id.hashValue
}

}

最后将Set添加到Array

finalAutoCompleteList = Array(namesAndIds)

关于swift - 相当于 Swift 中的 Java LinkedHashSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39073196/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com