刚开始使用 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"
(static
与final class
相同)
您可以在 Swift Programming Language 中阅读有关类型属性的更多信息书。
您当前的 println
失败,因为您正在尝试打印一个赋值,而不是一个字符串。我怀疑你的意思更像是:
println("ClassName is \"\(className)\"")
虽然 - 说了所有这些 - 如果您只想获得您应该使用的类的名称:
println(self.dynamicType)
关于xcode - 如何设置类范围变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089984/