如何在Swift 3中获取当前队列名称 [英] How to get the current queue name in swift 3

查看:481
本文介绍了如何在Swift 3中获取当前队列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在swift 2.2中我们具有类似的功能,用于使用当前正在运行的线程打印日志消息:

We have function like this in swift 2.2 for printing a log message with the current running thread:

func MyLog(_ message: String) {
    if Thread.isMainThread {
        print("[MyLog]", message)
    } else {
        let queuename = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))! // Error: Cannot convert value of type '()' to expected argument type 'DispatchQueue?'
        print("[MyLog] [\(queuename)]", message)
    }
}

这些代码不再在swift 3.0中编译.现在如何获取队列名称?

These code no longer compile in swift 3.0. How do we obtain the queue name now?

推荐答案

现在DispatchQueue具有标签属性.

在创建时分配给调度队列的标签.

The label you assigned to the dispatch queue at creation time.

var label: String { get } 


它似乎从一开始就存在,也许没有通过公共API公开.


It seems been existed from first, maybe not been exposed via public API.

macOS 10.10+

并且请仅使用此标签来获取人类可读的标签.不识别每个GCDQ.

And please use this only to obtain human-readable labels. Not to identify each GCDQ.

如果要检查代码是否在某些GCDQ上运行,可以使用

If you want to check whether your code is running on certain GCDQ, you can use dispatchPrecondition(...) function.

这篇关于如何在Swift 3中获取当前队列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆