我有一个对象数组。 我希望通过基于名称属性
比较对象来获取此数组中的不同元素class Item {
var name: String
init(name: String) {
self.name = name
}
}
let items = [Item(name:"1"), Item(name:"2"), Item(name:"1"), Item(name:"1"),Item(name:"3"), Item(name:"4")]
结果:
let items = [Item(name:"1"), Item(name:"2"),Item(name:"3"), Item(name:"4")]
我怎样才能在swift中做到这一点?
答案 0 :(得分:8)
这是一个Array扩展,用于根据给定的键返回唯一的对象列表:
extension Array {
func unique<T:Hashable>(by: ((Element) -> (T))) -> [Element] {
var set = Set<T>() //the unique list kept in a Set for fast retrieval
var arrayOrdered = [Element]() //keeping the unique list of elements but ordered
for value in self {
if !set.contains(by(value)) {
set.insert(by(value))
arrayOrdered.append(value)
}
}
return arrayOrdered
}
}
您可以这样做:
let uniqueBasedOnName = items.unique{$0.name}
答案 1 :(得分:1)
希望这会对你有所帮助:
class Item:Equatable, Hashable {
var name: String
init(name: String) {
self.name = name
}
var hashValue: Int{
return name.hashValue
}
}
func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.name == rhs.name
}
let items = [Item(name:"1"), Item(name:"2"), Item(name:"1"), Item(name:"1"),Item(name:"3"), Item(name:"4")]
var uniqueArray = Array(Set(items))
答案 2 :(得分:0)
在Swift中,您可以使用Equatable协议来区分对象数组中的唯一元素。
struct Item:Equatable{
var name:String
var price:Double
init(name:String,price:Double) {
self.name = name
self.price = price
}
static func ==(lhs: Item, rhs: Item) -> Bool{
return lhs.name == rhs.name
}
}
class ViewController: UIViewController {
var books = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
items.append(Item(name: "Example 1", price: 250.0))
items.append(Item(name: "Example 2", price: 150.0))
items.append(Item(name: "Example 1", price: 150.0))
items.append(Item(name: "Example 1", price: 150.0))
items.append(Item(name: "Example 3", price: 100.0))
items.unique().forEach { (item) in
print(item.name)
}
}
}
extension Sequence where Iterator.Element: Equatable {
func unique() -> [Iterator.Element] {
return reduce([], { collection, element in collection.contains(element) ? collection : collection + [element] })
}
}
答案 3 :(得分:0)
我使用了@Ciprian Rarau 的甜蜜回答,然后意识到如果元素不是唯一的,我什至不需要首先添加元素。所以我为此写了一个小扩展(受到答案的启发)。
extension Array {
public mutating func appendIfUnique<T: Hashable>(_ newElement: Element, check property: ((Element) -> (T))) {
for element in self {
if property(element) == property(newElement) { return }
}
append(newElement)
}
}
仅在唯一时附加元素:
array.appendIfUnique(newElement, check: { $0.name })