【问题标题】:Swift: Dictionary Key as CGRectSwift:字典键为 CGRect
【发布时间】:2015-07-10 23:31:50
【问题描述】:

我需要将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?)'

【问题讨论】:

  • self.points(boundsIndex) 需要为 self.points[boundsIndex]

标签: swift nsdictionary


【解决方案1】:

更新(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

【讨论】:

    【解决方案2】:

    通过扩展在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 作为密钥。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2017-11-27
    • 2015-09-03
    相关资源
    最近更新 更多