Swift 3 - How to write functions with no initialisers like the new UIColors?

前端 未结 6 603
再見小時候
再見小時候 2021-01-18 17:31

In previous versions of swift, you would get the colour white like this UIColor.whiteColor()

However, in Swift 3, you get the colour white without initi

相关标签:
6条回答
  • 2021-01-18 17:47

    You can use computed properties:

    extension UIColor {
        static var custom: UIColor {
            return UIColor(white: 0.5, alpha: 1)
        }
    }
    
    0 讨论(0)
  • 2021-01-18 17:49

    In Swift 3.0:

    in UIColor.white, white is a property and not a method/initializer

    In earlier swift versions:

    in UIColor.whiteColor(), white was a type method.

    0 讨论(0)
  • 2021-01-18 17:55

    When the compiler can infer the type of the value you are going to need, like here

    let a: Foo = ...
    

    you can use a static member (method, function, stored property, computed property) omitting the name of the type.

    So given this type

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

    you can write

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

    The same technique can be used when you pass a value to a function

    func doNothing(foo: Foo) { }
    

    Again the type of the parameter can be inferred by the compiler so instead of writing

    doNothing(foo: Foo.a)
    

    you can simply write

    doNothing(foo: .a)
    
    0 讨论(0)
  • 2021-01-18 17:58

    .whiteColor() is a static method (type method) on UIColor, whereas .white is a static (computed in my example) property on UIColor. The difference in defining them looks like:

    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)
      }
    }
    
    0 讨论(0)
  • 2021-01-18 18:02

    Use a stored class property instead of a computed class property.

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

    --

    NOTE: Old answer. Previously Objective C didn't allow for class properties, now it does.

    Like others have said, it's a property.

    If you're only using Swift (no Objective C), then you can use a regular class property instead of a computed property.

    extension UIColor {
        @nonobjc static let custom = UIColor(white: 0.5, alpha: 1)
    }
    
    0 讨论(0)
  • 2021-01-18 18:03

    They are properties, not functions.

    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) }
    }
    
    0 讨论(0)
提交回复
热议问题