【问题标题】:Finding which instance of struct is selected查找选择了哪个结构实例
【发布时间】:2018-02-22 08:26:55
【问题描述】:

我有一个结构

 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是否包含citiestowns并打印出位置, 我在我用于didSelectItemAt indexPath的collectionView中尝试了这个@

if (self.area == self.cities)
{
  Print ("This is a city")
} 
else
{
   Print ("This is a town")
}

编译失败并出现给定错误,

二元运算符 '==' 不能应用于两个 '[Area]' 操作数

【问题讨论】:

  • 你想比较两个 Area 结构数组?
  • 你能解释一下你的逻辑吗?选定的 collectionView 单元格成为城市的确切标准是什么。你的collectionView的数据源是什么?城市或城镇?还是其他一些 Area 类型的数组?
  • @ReinierMelian,不,我不想比较,但要找出所选项目是否来自city oir town。
  • “它抛出一个错误”。你的意思是编译失败并出现给定的错误。 “抛出错误”是指正在运行的程序使用throw 语句。
  • @JeremyP,感谢您指出差异,刚刚编辑了问题。

标签: ios swift xcode struct


【解决方案1】:

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

解决方案 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")
    }

希望对你有帮助

【讨论】:

  • 在两个字符串属性上对 hashValue 进行异或不是更好吗?喜欢:return name.hashValue ^ image.hashValue。我们不能假设两个实例只是因为哈希匹配就像现在这样吗?
  • @Alex : 我同意 :) 想法只是为了向 OP 展示如何使用 Set 来解决问题 :) OP 可以根据他的需要修改它:) 但我同意你的观点:)跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 2020-04-21
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
相关资源
最近更新 更多