刚开始使用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
。例如,在我的视图控制器中,当用户单击按钮时,我可以执行Hello.someFunc()
。
提前感谢您的帮助。
答案 0 :(得分:2)
如果您想允许子类覆盖它:
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)
答案 1 :(得分:1)
您需要将类变量声明为静态,您可以使用self在类级别方法中访问它。但是,如果要从实例方法访问它,则必须使用类名。
jQuery.post(ajaxurl, data, function(response){
console.log(response);
$( "#edu_programme" ).autocomplete({
response
});
});
另请注意,swift期望在创建类变量时对其进行初始化。