iOS - 如何在不初始化 Swift 类的情况下调用方法?

标签 ios swift

<分区>

在 Swift 中调用方法而不初始化类的一个完美示例是 UIColor

您可以执行 UIColor.whiteColor()。请注意 () 如何位于 whiteColor 的末尾。

如果我要为自定义方法扩展 UIColor:

extension UIColor {
    /** Set the color to white. */
    func white() -> UIColor {
        return UIColor.whiteColor()
    }
}

我必须像这样调用此方法:UIColor().white() 而不是这样的 UIColor.white()

如何编写初始化程序仅在末尾的方法?还是仅当类是用 Objective-C 编写时才可用?

最佳答案

您需要将该函数设为静态 函数。例如:

extension UIColor {
    /** Set the color to white. */
    class func white() -> UIColor {
        return UIColor.whiteColor()
    }
}

您也可以使用单词 static 代替 class。

关于iOS - 如何在不初始化 Swift 类的情况下调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38536593/

相关文章:

arrays - 如何快速从数组中获取对象

ios - 使用完成 block ,而不是返回变量 - iOS Swift

ios - 在 iOS 和 Swift 中使用 NSNumberFormatter 获取语言环境

ios - Bolts Framework的使用方法[Facebook+Parse]

ios - 以编程方式加载新的 ViewController

javascript - jQuery Chained - 不适用于 iOS

swift - requestWhenInUseAuthorization() 在 iOS 8 中无法使用 Info.plist 中的 NSLocationWhenInUseUsageDescription 键

ios - 在 Instruments 中录音时应用程序崩溃

ios - 如何在 TableView 中快速设置新对象?

android - 当设备处于 sleep 状态时对敲击电话执行操作?