小编Ale*_*ant的帖子

Swift中的扩展功能,扩展静态功能和扩展类功能有什么区别?

我试图在UIColor上创建一个扩展函数,该函数可以采用Card.Colour类型的参数并将UIColor返回给调用方。

button.backgroundColor = UIColor.getColour(cardColour: cardToDeal.colour)


extension UIColor {
    func getColour(cardColour: Card.Colour) -> UIColor {
        switch cardColour {
        case .Red:
            return UIColor.red
        case .Green:
            return UIColor.green
        case .Blue:
            return UIColor.blue
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试执行此操作时,UIColor.getColour的扩展功能要求我在扩展方法中输入UIColor类型的参数,而不是Card.Colour的指定类型。

但是,当我将getColour的扩展功能更改为:

static func getColour(cardColour: Card.Colour) -> UIColor {
class func getColour(cardColour: Card.Colour) -> UIColor {
Run Code Online (Sandbox Code Playgroud)

它允许我传递Card.Colour类型的参数

为什么是这样?为什么将函数更改为静态函数或类函数会更改需要传入的类型?

提前致谢!

(详细的答案将不胜感激)

swift swift-extensions

2
推荐指数
1
解决办法
403
查看次数

标签 统计

swift ×1

swift-extensions ×1