Swift类中的静态vs类函数/变量? [英] Static vs class functions/variables in Swift classes?

查看:271
本文介绍了Swift类中的静态vs类函数/变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在Swift 1.2中编译:

The following code compiles in Swift 1.2:

class myClass {
    static func myMethod1() {
    }
    class func myMethod2() {
    }
    static var myVar1 = ""
}

func doSomething() {
    myClass.myMethod1()
    myClass.myMethod2()
    myClass.myVar1 = "abc"
}

静态函数和函数之间有什么区别?我应该使用哪一个,何时?

What is the difference between a static function and a class function? Which one should I use, and when?

如果我尝试定义另一个变量 class var myVar2 = ,它说:

If I try to define another variable class var myVar2 = "", it says:


类中还不支持类存储的属性;

Class stored properties not yet supported in classes; did you mean 'static'?

当支持此功能时,静态变量和变量(即两者都在类中定义)?我应该使用哪一个,以及何时?

When this feature is supported, what will the difference be between a static variable and a class variable (i.e. when both are defined in a class)? Which one should I use, and when?

(Xcode 6.3)

(Xcode 6.3)

推荐答案

static class 都将方法与类关联,而不是类的实例。区别是子类可以覆盖 class 方法;它们不能覆盖 static 方法。

static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.

理论上函数以相同的方式(子类可以覆盖它们),但是它们在Swift中是不可能的。

class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet.

这篇关于Swift类中的静态vs类函数/变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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