xcode - 如何设置类范围变量?

标签 xcode swift

刚开始使用 Swift,我正在创建一个 API 服务类,但我不明白如何才能让它工作!?!

import UIKit

class Hello {
    var className: String

    init() {
        self.className = "hello"
    }

    class func someFunc() {
        println(self.className = "hello") // <= This doesn't work
    }      
}

据我所知,因为我需要在调用它时可以访问 someFunc,所以我需要它具有 class func。例如,在我的 View Controller 中,当用户单击按钮时,我可以执行 Hello.someFunc()

在此先感谢您的帮助。

最佳答案

如果你想让子类能够覆盖它:

class var className: String { return "Hello" }

(注意 class 变量不能是 stored 属性;它们必须是 computed 属性。)

否则:

static var className = "Hello"

(staticfinal class 相同)

您可以在 Swift Programming Language 中阅读有关类型属性的更多信息书。

您当前的 println 失败,因为您正在尝试打印一个赋值,而不是一个字符串。我怀疑你的意思更像是:

println("ClassName is \"\(className)\"")

虽然 - 说了所有这些 - 如果您只想获得您应该使用的类的名称:

println(self.dynamicType)

关于xcode - 如何设置类范围变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089984/

相关文章:

ios - 在 UIActivityViewController 中更改 UIBarButtonItems 的色调

autolayout - 在 Swift 中使用自动布局视觉格式?

ios - 将现有的 iOS 应用程序项目拆分为静态库和应用程序皮肤项目

ios - .framework 和 .a 中的重复符号

ios - xcode 5中的instanceViewControllerWithIdentifier

swift - 我应该在 self 被释放时调用完成处理程序吗

ios - 如何在 Interface Builder 预览 Storyboard中显示导航栏(助理编辑器)

xcode - 尝试编译 Chess.app 时出现构建错误

ios - 获取一个 UITableView 以在标题顶部加载

swift - Swift 中运算符重载的多态性