Swift:字典键为CGRect

时间:2015-07-10 23:31:51

标签: swift nsdictionary

我需要将frame的{​​{1}}保存为密钥,将button保存为数组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(); }

2 个答案:

答案 0 :(得分:3)

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

extension CGRect: Hashable {
    public var hashValue: Int {
        return NSStringFromCGRect(self).hashValue
    }
}

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

答案 1 :(得分:0)

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

在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