2015-07-10 41 views
0

我需要將buttonframe保存爲密鑰,將index保存爲value。下面是代碼:Swift:Dictionary Key as CGRect

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'

UPDATE

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?)'

+1

self.points(boundsIndex)需要self.points [boundsIndex] –

回答

3

實施Hashable協議CGRect通過擴展。

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

它將允許您使用CGRect作爲關鍵。

+0

我試過這個在同一個類,但我得到一個錯誤:'使用未解析的標識符'NSStringFromRect'' – user1107173

+0

您是否已經導入Foundation? –

+0

是和UIKit。 – user1107173