简体   繁体   English

实现swift equatable协议给我带来了错误的访问错误。 为什么?

[英]Implementing swift equatable protocol gives me bad access error. why?

here is my code. 这是我的代码。 it seems that when i subclass UIColor to make it equatable i get a memory error. 似乎当我将UIColor子类化为使其等同时,我得到一个内存错误。 why is that? 这是为什么?

class MyColor: UIColor, Equatable {
    var name: String


    init(name: String, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
        self.name = name
        super.init(red: r, green: g, blue: b, alpha: a)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

func == (lhs: MyColor, rhs: MyColor) -> Bool {
    return lhs.name == rhs.name
}

let test1 = MyColor(name: "coolRed", r: 10, g: 12, b: 22)

let test2 = MyColor(name: "coolBlue", r: 10, g: 12, b: 22)


if test1 == test2 {
    println("hey")
}

在此输入图像描述

UIColor is a class cluster, subclassing should be avoided. UIColor是一个类集群,应该避免使用子类。

You could use the Objective-C runtime to get the functionality you desire. 您可以使用Objective-C运行时来获得所需的功能。

This snippet is "playground-ready". 这个片段是“准备好游乐场”。

import UIKit

let _nameKey = malloc(4)

extension UIColor : Equatable {

var name : String {
    get {
        return objc_getAssociatedObject(self, _nameKey) as! String
    }
    set {
         objc_setAssociatedObject(self,
            _nameKey,
            newValue,
            UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        );
    }
}
}


public func ==(lhs: UIColor, rhs: UIColor) -> Bool {
    return lhs.name == rhs.name
}

let aRed = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.0)
aRed.name = "Red"
aRed.name

let anotherRed = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.0)
anotherRed.name = "Red"

aRed == anotherRed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM