我有一个结构
struct Area{
var name = String()
var image = String()}
var area = [Area]()
然后我创建了它的两个实例
let cities = [Area(name:"CityA",image:"CityImgA"), Area(name:"CityB",image:"CityImgB"), Area(name:"CityC",image:"CityImgC") ]
let towns = [Area(name:"TownA",image:"TownImgA"), Area(name:"TownB",image:"TownImgB"), Area(name:"TownC",image:"TownImgC")]
如何找出area
是否包含cities
或towns
并打印出位置,
我在用于didSelectItemAt indexPath
if (self.area == self.cities)
{
Print ("This is a city")
}
else
{
Print ("This is a town")
}
编译因给定错误
而失败二元运算符' =='不能适用于两个[区域]'操作数
答案 0 :(得分:3)
可能有多种解决方案,简单就是
解决方案1:
写一个扩展名到数组
extension Array where Element: Equatable {
func contains(array: [Element]) -> Bool {
for item in array {
if !self.contains(item) { return false }
}
return true
}
}
最后将您的数组比较为
if cities.contains(array: areas) {
print("cities")
}
else {
print("towm")
}
解决方案2:
第二个解决方案是使用Set
转换结构以确认Hashable
协议
struct Area : Hashable {
static func ==(lhs: Area, rhs: Area) -> Bool {
return lhs.name == rhs.name
}
var hashValue: Int {
return name.hashValue
}
var name = String()
var image = String()
}
最后转换城市和区域以设置和使用isSubset
let citiesSet = Set(cities)
let areaSet = Set(areas)
if areaSet.isSubset(of: citiesSet) {
print("cities")
}
else {
print("towm")
}
希望有所帮助