2016-09-23 32 views
4

在迅速的早期版本,你会得到的白色像这样UIColor.whiteColor()Swift 3 - 如何编写新的UIColors等没有初始化函数的函数?

然而,斯威夫特3,你得到的颜色白色无initialisers像这样UIColor.white

我怎么会写此相同的功能,而无需使用初始值,如UIColor.custom

extension UIColor { 
    func custom() { 
     return UIColor(white: 0.5, alpha: 1) 
    } 
} 
+2

在斯威夫特2,'whiteColor()'是一类功能。在Swift 3中,'white'是一个类变量。 (这不是关于* initialisers *)。 – Codo

回答

5

您可以使用computed properties

extension UIColor { 
    static var custom: UIColor { 
     return UIColor(white: 0.5, alpha: 1) 
    } 
} 
+0

这可能是对的,但编译器会强制你在你的颜色(变量)名称上使用大写字母,因为它的静态。我想知道为什么从UIKit获得的内置颜色没有大写字母:UIColor.red您怎么看? – knutigro

+0

@knutigro你有什么资料吗?我在操场上面试过了上面的代码,它工作正常。在我的一个项目中,我经常使用类似的代码,它编译没有错误。根据API设计指南,'var's应该以小写字母开头。 – FelixSFD

+1

阿哈对此抱歉。我现在意识到,我从我安装的一个叫做Swift-Clean http://www.swiftcleanapp.com的三方应用程序中得到了这个警告。我猜他们还没有和Swift 3保持同步。 – knutigro

3
.whiteColor()

UIColor一个static method (type method),而.whiteUIColor静态(computed in my example) property。在定义它们的区别是这样的:

struct Color { 
    let red: Int 
    let green: Int 
    let blue: Int 

    static func whiteColor() -> Color { 
    return Color(red: 255, green: 255, blue: 255) 
    } 

    static var white: Color { 
    return Color(red: 255, green: 255, blue: 255) 
    } 
} 
2

它们的属性,而不是功能。

import UIKit 

extension UIColor { 
    // Read-only computed property allows you to omit the get keyword 
    static var custom: UIColor { return UIColor(white: 0.5, alpha: 1) } 
} 
2

在夫特3.0:

UIColor.whitewhite属性而不是一个方法/初始化

在早期迅速版本:

UIColor.whiteColor()

white是一个type method

0

像其他人一样,这是一个属性。

如果你只使用Swift(没有Objective C),那么你可以使用普通的类属性而不是计算属性。

extension UIColor { 
    @nonobjc static let custom = UIColor(white: 0.5, alpha: 1) 
} 
0

当编译器可以推断你将需要的值的类型,像这里

let a: Foo = ... 

可以使用静态成员(方法,功能,存储的属性,计算属性)省略类型的名称。

所以给定的这种类型

class Foo { 
    static let a = Foo() 
    static var b = Foo() 
    static var c:Foo { return Foo() } 
    static func d() -> Foo { return Foo() } 
} 

可以写

let a: Foo = .a 
let b: Foo = .b 
let c: Foo = .c 
let d: Foo = .d() 

当值传递给函数

func doNothing(foo: Foo) { } 

同样类型的相同的技术可用于该参数可以由编译器推断,以代替编写

doNothing(foo: Foo.a) 

可以简单的写

doNothing(foo: .a)