我正在为 ipad 试验 Swift Playgrounds,我正在尝试制作一个基本计时器,这是我使用的代码
import UIKit
import ObjectiveC
import CoreFoundation
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()
class StopWatch {
var myCounter = 0
func timer() {
var timer = Timer.scheduledTimer(
timeInterval: 1,
target: self,
selector: Selector("incrementCounter:"),
userInfo: nil,
repeats: true
)
}
@objc func incrementCounter(mytimer:Timer) {
myCounter = myCounter + 1
print(myCounter)
}
}
var myStopWatch = StopWatch()
myStopWatch.timer()
然而,每次我运行它时,它都会反复出现错误。我认为这是因为 import xcPlaygrounds 在 swift playgrounds for ipad 以及它附带的所有功能和命令中不可用我想知道是否有此模块的替代品或更好的方法。
谢谢
最佳答案
如果你使用 playground 和 swift3,你可以使用下面的代码。
'XCPSetExecutionShouldContinueIndefinitely' 已弃用,所以我添加了
PlaygroundSupport 模块并将 needsIndefiniteExecution 值设置为 true。
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class StopWatch {
var myCounter = 0
func timer() {
let _ = Timer.scheduledTimer( timeInterval: 1, target: self, selector: #selector(incrementCounter(mytimer:)), userInfo: nil, repeats: true)
}
@objc func incrementCounter(mytimer:Timer) {
myCounter = myCounter + 1
print(myCounter)
}
}
var myStopWatch = StopWatch()
myStopWatch.timer()
关于swift - 有 XCPlayground 的替代品吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863531/