Swift 3 - 如何编写没有初始化程序的函数,比如新的UIColors? [英] Swift 3 - How to write functions with no initialisers like the new UIColors?

查看:130
本文介绍了Swift 3 - 如何编写没有初始化程序的函数,比如新的UIColors?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以前的swift版本中,您会得到像这样的颜色: UIColor.whiteColor()

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

然而,在Swift 3中,你会得到没有初始值的白色,例如 UIColor.white

However, in Swift 3, you get the colour white without initialisers like so UIColor.white

这个函数不需要使用初始化函数,如 UIColor.custom

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


推荐答案

您可以使用计算属性

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

这篇关于Swift 3 - 如何编写没有初始化程序的函数,比如新的UIColors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆