2016-07-22 85 views
0

在Swift中没有初始化类的调用方法的一个完美例子是UIColor。你可以做UIColor.whiteColor()。请注意0​​是如何在whiteColor的末尾。iOS - 如何在不初始化Swift类的情况下调用方法?

如果我延长UIColor自定义方法:

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

我会打电话给这样的方法,以便:UIColor().white(),而不是像这样UIColor.white()

我该如何编写初始化程序只在最后的方法?或者只有当这个类用Objective-C编写时才可用?

+0

他们已经在Swift 3为你做了这些 –

回答

3

您需要使该功能为classstatic功能。例如:

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

您还可以使用单词static而不是类。

相关问题