Swift - 在类中引用类的类型

标签 swift

当在类型的实例方法中使用静态类型属性和方法时,我经常重复类型的名称。

例如

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/

相关文章:

ios - 我无法导入我需要的东西,以使用 MaterialContainerScheme

swift - 强制 TableView 单元格到一页上

dictionary - 类型 '[String, AnyObject?]' 不符合 AnyObject 协议(protocol)? : why?

swift - 如何寻找一个不知名的 child

swift - swift Foundation 中的第 5747 行是“public typealias ObservableObject = ObservableObject”,为什么?

xcode - 在应用程序和扩展程序之间快速传输变量

ios - 以编程方式快速创建带有约束的 UIbutton

ios - 如何使用 Xcode 7 beta 编译旧的 Swift 代码?

swift - 如果条件为真时语句未运行

Swift 4 使用计时器接收推送通知