Swift 3 - How to write functions without initializers, such as new UIColors?

In previous versions of swift, you would get white as UIColor.whiteColor()

However, in Swift 3 you will get white without initializers, for example: UIColor.white

How would I write the same function without using initializers, how UIColor.custom?

extension UIColor {
    func custom() {
        return UIColor(white: 0.5, alpha: 1)
    }
}
+4
source share
6 answers

You can use the computed properties :

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

.whiteColor()is a static method (type method) on UIColor, whereas .whiteis a static (calculated in my example) property in UIColor. The difference in their definition looks like this:

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)
  }
}
+3

, .

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

Swift 3.0:

UIColor.white, white - , /

:

UIColor.whiteColor(), white type method.

+2

, .

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)
0

Source: https://habr.com/ru/post/1655605/


All Articles