当在类型的实例方法中使用静态类型属性和方法时,我经常重复类型的名称。
例如
class Foo
{
// Type properties, methods
static let kBrandColor = UIColor.red
static let kMeaning = 42
static func makeThing() -> Thing { ... }
// Instance method
func printStuff()
{
print("Brand Color is: \(Foo.kBrandColor)")
print("The meaning of life is: \(Foo.kMeaning)")
let thing = Foo.makeThing()
print("Thing is \(thing)"
}
...
}
这些对“Foo”的重复引用可能(并且经常)在复制粘贴、重构时导致错误。很容易忘记更改“Foo”,但代码仍然可以编译。
所以,我一直在使用这样的模式:
class Foo
{
fileprivate typealias _ThisClass = Foo
// Type properties, methods
static let kBrandColor = UIColor.red
static let kMeaning = 42
static func makeThing() -> Thing { ... }
// Instance method
func printStuff()
{
print("Brand Color is: \(_ThisClass.kBrandColor)")
print("The meaning of life is: \(_ThisClass.kMeaning)")
let thing = _ThisClass.makeThing()
print("Thing is \(thing)"
}
...
}
这种方法具有一定的复制粘贴安全性的优点,但代价是牺牲了一些样板文件。
是否有更好、更干净的解决方案来解决这个问题? (我尝试过搜索,但是为此类问题找到正确的搜索词非常棘手。)
最佳答案
协议(protocol)在这里可以很好地发挥作用。您可以定义协议(protocol)所需的属性,然后将其应用到您想要使用这些属性的任何类。
protocol Brandable {
var kBrandColor: UIColor { get }
var kMeaning: Int { get }
}
class Foo: Brandable {
let kBrandColor: UIColor = .red
let kMeaning: Int = 42
}
如果你想重用 printStuff 函数,你也可以将其放入协议(protocol)中,并将基本实现放入扩展中:
protocol Brandable {
var kBrandColor: UIColor { get }
var kMeaning: Int { get }
func printStuff()
}
extension Brandable {
func printStuff() {
print("Brand Color is: \(kBrandColor)")
print("The meaning of life is: \(kMeaning)")
}
}
class Foo: Brandable {
let kBrandColor: UIColor = .red
let kMeaning: Int = 42
}
class Bar: Brandable {
let kBrandColor: UIColor = .blue
let kMeaning: Int = 100
}
Foo().printStuff()
Bar().printStuff()
使用 makeStuff() 函数也可以完成同样的操作。共享功能包含在协议(protocol)及其扩展中。如果您需要更改某些类中的行为,您只需添加自己的 printStuff 或 makeStuff 函数来覆盖协议(protocol)的默认实现。
关于Swift - 在类中引用类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201342/