尚不支持类变量 [英] Class variables not yet supported

查看:36
本文介绍了尚不支持类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以拆分视图控制器作为初始视图控制器开始我的项目,并从故事板自动启动它.

I begin my project with a split view controller as initial view controller and start it automatically from storyboard.

通常,具有此 UI 的应用具有一个且只有一个拆分视图控制器作为 root,因此我在子类中创建了一个 静态变量 并在初始化时设置它完成.

Generally, an app with this UI have one and only one split view controller as root, so I create a static variable in the subclass and set it when initialisation was done.

所以我想快速尝试这种行为.

So I want try this behaviour with swift.

我在 iBook 上阅读了有关 Type 属性(带有 static 和 class 关键字)的 Swift 编程语言指南,并尝试了一段代码来完成这项工作:

I read the Swift programming language guide book on iBook about Type properties (with static and class keyword) and trying a piece of code to the job:

import UIKit

class SplitViewController: UISplitViewController {

    class func sharedInstance() -> SplitViewController {
        return SplitViewController.instance
    }

    class let instance: SplitViewController = nil

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.initialization()
    }

    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder);
        self.initialization()
    }

    func initialization() {
        SplitViewController.instance = self;
    }
}

但是当 Xcode 说不支持类型属性的 class 关键字时,我发现了.

but I figured out when Xcode say the class keyword for type properties wasn't supported yet.

您有解决方案吗?

推荐答案

Swift 现在支持类中的静态变量.这与类变量并不完全相同(因为它们不是由子类继承的),但它让您非常接近:

Swift now has support for static variables in classes. This is not exactly the same as a class variable (because they aren't inherited by subclasses), but it gets you pretty close:

class X {
  static let y: Int = 4
  static var x: Int = 4
}

println(X.x)
println(X.y)

X.x = 5

println(X.x)

这篇关于尚不支持类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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