我找到了 this question并尝试将代码复制到我的 Xcode 项目,但我收到以下错误消息。
error: use of unresolved identifier 'self'
什么是正确的方法?
编辑:这里是在 Playground 上测试过的代码:
//: Playground - noun: a place where people can play
import Cocoa
import Foundation
func sayHello() {
print("hello World")
}
var SwiftTimer = NSTimer()
SwiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)
最佳答案
通常对属性名使用大写被认为是一种不好的态度,你应该使用swiftTimer。
这些表达式不允许出现在顶层:
var swiftTimer = NSTimer()
swiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)
你必须把它放在一个函数中,例如:
override func viewDidLoad() {
super.viewDidLoad()
var swiftTimer = NSTimer()
swiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)
}
关于swift - 使用 NSTimer 的重复函数失败,目标为 : self in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375939/