Swift:作为 CGRect 的字典键

Swift: Dictionary Key as CGRect

我需要将 buttonframe 保存为键,并将数组中的 index 保存为其 value。下面是代码:

var buttonLocationWithIndex = Dictionary<CGRect, Int>()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    for (index, point) in enumerate(self.points){
        let pointButton = UIButton()
        pointButton.frame = point.bounds
        self.buttonLocationWithIndex[point.frame] = index
        self.view.addSubview(pointButton)
    }

我在尝试声明字典时遇到错误:Type 'CGRect' does not confirm to protocol 'Hashable'

更新

func pressed(sender: UIButton!) {
    var alertView = UIAlertView();

    alertView.addButtonWithTitle("Ok");
    alertView.title = "title";
    var boundsIndex = self.buttonLocationWithIndex[sender.frame]
    var value = self.points(boundsIndex)
    alertView.message = value
    alertView.show();
}

错误: Cannot invoke points with an arguments list of type (Int?)'

通过扩展在 CGRect 上实施 Hashable 协议。

extension CGRect: Hashable {
    public func hash(into hasher: inout Hasher) {
        hasher.combine(origin.x)
        hasher.combine(origin.y)
        hasher.combine(size.width)
        hasher.combine(size.height)
    }
}

它将允许您使用 CGRect 作为密钥。

更新 (2021-11-01): 已接受的答案经过编辑以提供与我的类似的解决方案,因此它也有效。


这是一个老问题,但由于我最近需要这个,所以我认为这可能对其他人有用。

目前在Swift 5中为CGRect实现Hashable协议的方式是:

import UIKit

extension CGRect: Hashable {
    public func hash(into hasher: inout Hasher) {
        hasher.combine(minX)
        hasher.combine(minY)
        hasher.combine(maxX)
        hasher.combine(maxY)
    }
}

来源:https://developer.apple.com/documentation/swift/hashable