//日志打印
func log<T>(_ msg: T,
file: NSString = #file,
line: Int = #line,
fn: String = #function) {
#if DEBUG
let prefix = "\(file.lastPathComponent)_\(line)_\(fn)"
// prefix + (msg as! String)
print(prefix,msg)
#endif
}
//GCD异步函数封装
public typealias Task = () -> Void
public struct Asynchrony {
public static func async(_ task: @escaping Task) {
_async(task)
}
public static func async(_ task: @escaping Task,
_ mainTask: @escaping Task){
_async(task, mainTask)
}
private static func _async(_ task: @escaping Task,
_ mainTask: Task? = nil){
let item = DispatchWorkItem(block: task)
DispatchQueue.global().async(execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
}
@discardableResult
public static func delayOnAsyncThread(_ seconds: Double,
_ task: @escaping Task) -> DispatchWorkItem {
_delay(seconds, task)
}
@discardableResult
public static func delayOnAsyncThread(_ seconds: Double,
_ task: @escaping Task,
_ mainTask: @escaping Task) -> DispatchWorkItem {
_delay(seconds, task, mainTask)
}
@discardableResult
private static func _delay(_ seconds: Double,
_ task: @escaping Task,
_ mainTask: Task? = nil) -> DispatchWorkItem{
let item = DispatchWorkItem(block: task)
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + seconds, execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
return item
}
@discardableResult
public static func delayOnMainThread(_ seconds: Double,
_ task: @escaping Task) -> DispatchWorkItem{
let item = DispatchWorkItem(block: task)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds, execute: item)
return item
}
}
func testAsync() {
Asynchrony.async{ print(Thread.current) }
Asynchrony.async ({
print(Thread.current)
}){
print(Thread.current)
}
Asynchrony.delayOnAsyncThread(1, {
print("async delay 1",Thread.current)
})
Asynchrony.delayOnAsyncThread(2) {
print("async delay 2",Thread.current)
} _: {
print("async delay 2, call back on main",Thread.current)
}
Asynchrony.delayOnMainThread(3) {
print("async on main Thread delay 3",Thread.current)
}
}
网友评论