Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 查找所选结构的哪个实例_Ios_Swift_Xcode_Struct - Fatal编程技术网

Ios 查找所选结构的哪个实例

Ios 查找所选结构的哪个实例,ios,swift,xcode,struct,Ios,Swift,Xcode,Struct,我有一个结构 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(na

我有一个结构

 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")]
如何确定
地区
是否包含
城市
城镇
并打印出位置, 我在用于
didselectitematindexpath

if (self.area == self.cities)
{
  Print ("This is a city")
} 
else
{
   Print ("This is a town")
}
编译失败,出现给定错误

二进制运算符“==”不能应用于两个“[Area]”操作数


可能有多种解决方案,简单的一种是

解决方案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
将结构转换为confirm
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")
    }

希望对您有所帮助

您想比较两个区域结构数组吗?您能解释一下您的逻辑吗?选定的collectionView单元成为城市的标准是什么。您的collectionView的数据源是什么?城市还是城镇?还是其他区域类型的数组?@ReinierMelian,不,我不想比较,但想知道所选项目是否来自城市或城镇。“它抛出了一个错误”。您的意思是编译失败并出现给定的错误。“抛出错误”是指正在运行的程序使用了
throw
语句。@JeremyP,感谢您指出了其中的区别,刚刚编辑了问题。在两个字符串属性上对哈希值进行异或不是更好吗?例如:
返回name.hashValue^image.hashValue
。我们不能假设两个实例在散列匹配时是相同的,就像现在一样?@Alex:我同意:)这个想法只是为了向OP展示如何使用Set来解决这个问题:)OP可以根据他的需要修改它:)但我同意你的观点:)