使用app项目 编译如下代码
//延时1s 输出
let time=Timer(timeInterval: 1.0, repeats: false) { (timer) in
print("Timer in a block.")
}
time.fire()
//延时1s 循环输出
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
print("scheduledTimer in a block")
}
//
// ViewController.swift
// DemoApp
//
// Created by liuan on 2020/4/23.
// Copyright © 2020 anguo.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var appleCount=0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//延时1s 循环输出
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerAction(_:)), userInfo: "an apple", repeats: true)
}
@objc func timerAction(_ timer:Timer){
if self.appleCount==3{
//停止计时器
timer.invalidate()
return
}
let parameter=timer.userInfo
print("I'm eating \(parameter!).")
self.appleCount+=1
}
}