gpt4 book ai didi

ios - 实现 swift equatable 协议(protocol)给我错误的访问错误。为什么?

转载 作者:搜寻专家 更新时间:2023-10-31 22:50:24 24 4
gpt4 key购买 nike

这是我的代码。似乎当我将 UIColor 子类化以使其相等时,我得到了一个内存错误。这是为什么?

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")
}

enter image description here

最佳答案

UIColor 是类簇,应避免子类化。

您可以使用 Objective-C 运行时来获得您想要的功能。

这个片段是“ Playground 就绪”。

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

关于ios - 实现 swift equatable 协议(protocol)给我错误的访问错误。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30089467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com