Swift中的类方法是在类级别上定义的方法,可以在不创建类的实例的情况下调用。类方法使用关键字classstatic来声明。

下面是一个示例,演示了如何定义和调用类方法:

class MathUtils {
    class func factorial(of number: Int) -> Int {
        if number <= 0 {
            return 1
        } else {
            return number * factorial(of: number - 1)
        }
    }
}

let result = MathUtils.factorial(of: 5)
print(result) // 输出: 120

在上面的示例中,我们定义了一个名为factorial的类方法。该方法计算给定数的阶乘。通过使用MathUtils.factorial(of: 5)的方式,我们可以直接调用类方法来计算5的阶乘。

swift 类方法

原文地址: https://www.cveoy.top/t/topic/hFi0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录