Yellow Yellow - 1 month ago 19
Swift Question

Is there a replacement for XCPlayground?

I am experimenting with Swift Playgrounds for ipad and i am attempting to make a basic timer this is the code im using

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()


However it repeatedly comes up with and error every time i run it. This i believe is because import xcPlaygrounds is unavailable in swift playgrounds for ipad along with all the functions and commands that come with it i was wondering if there is a replacement for this Module or a better way of doing this.

Thanks

Answer

If you are using playground with swift3, you can use the code below.

'XCPSetExecutionShouldContinueIndefinitely' is deprecated so I added

PlaygroundSupport module and set needsIndefiniteExecution value to 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()
Comments