在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 中做到这一点?!
我已经看到Swift 的 API 中是否存在一种从数组中删除重复元素的简单方法?
当我将 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
}
}