Swift 3 - How to write functions with no initialis

2019-02-23 15:50发布

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 initialisers like so UIColor.white

How would I write this same function without having to use initialisers, as UIColor.custom ?

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

6条回答
太酷不给撩
2楼-- · 2019-02-23 16:28

.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)
  }
}
查看更多
别忘想泡老子
3楼-- · 2019-02-23 16:34

You can use computed properties:

extension UIColor {
    static var custom: UIColor {
        return UIColor(white: 0.5, alpha: 1)
    }
}
查看更多
放我归山
4楼-- · 2019-02-23 16:42

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) }
}
查看更多
孤傲高冷的网名
5楼-- · 2019-02-23 16:47

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)
}
查看更多
6楼-- · 2019-02-23 16:51

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)
查看更多
Explosion°爆炸
7楼-- · 2019-02-23 16:55

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.

查看更多
登录 后发表回答