Swift中字符串常量的String Formatter?

时间:2023-01-14 18:34:10

Sorry if this is a duplicate, but I tried searching around including Apple's String Format Specifiers, and IEEE printf spec but couldn't find the answer for something this simple.

很抱歉,如果这是重复的,但我尝试搜索包括Apple的字符串格式说明符和IEEE printf规范,但找不到这么简单的答案。

I would like to print os_log message with string formatter for string constant. Something akin to:

我想用字符串格式化程序打印os_log消息,用于字符串常量。类似于:

printf("Currently at processing state: %s\n", "reading in");

in C. However, when I tried something like this in Swift:

在C.但是,当我在Swift中尝试这样的事情时:

os_log("Currently at processing state: %s", log: .default, type: .info, "reading in")

it simply printed nothing out at all.

它根本没有印刷任何东西。

How do I print a string constant using string format specifier? I'm not sure how to do it with NSLog either.

如何使用字符串格式说明符打印字符串常量?我不确定如何使用NSLog。

Edit: os_log requires StaticString, so it can't do something like "Something \(Expr) Something else" like in print(). You can still use string formatting to print number variables. I'm wondering how to print string constants / variables in this case.

编辑:os_log需要StaticString,所以它不能像print()中的“Something \(Expr)Something”那样做。您仍然可以使用字符串格式来打印数字变量。我想知道在这种情况下如何打印字符串常量/变量。

Edit 2: Apple actually has discussion on this topic right on its manual page, which I managed to miss it because but it's only discussed in the Objective-C API version for now.

编辑2:Apple实际上已经在其手册页面上讨论了这个主题,我设法错过了它,但它现在仅在Objective-C API版本中讨论过。

2 个解决方案

#1


9  

From the os_log man page:

从os_log手册页:

You may also use the "%@" format specifier for use with Obj-C/CF/Swift objects

您也可以使用“%@”格式说明符与Obj-C / CF / Swift对象一起使用

In your case

在你的情况下

import os.log

os_log("Currently at processing state: %@", log: .default, type: .info, "reading in")

works because the Swift string is bridged to NSString on a variable argument list.

因为Swift字符串在变量参数列表上桥接到NSString,所以可以正常工作。

#2


-4  

This will work:

这将有效:

print("Currently at processing state: \(readingin)")

So you put the parameter you want to print for readingin.

因此,您要将要打印的参数用于阅读。

(If this solved your question please mark it as the answer)

(如果这解决了您的问题,请将其标记为答案)

#1


9  

From the os_log man page:

从os_log手册页:

You may also use the "%@" format specifier for use with Obj-C/CF/Swift objects

您也可以使用“%@”格式说明符与Obj-C / CF / Swift对象一起使用

In your case

在你的情况下

import os.log

os_log("Currently at processing state: %@", log: .default, type: .info, "reading in")

works because the Swift string is bridged to NSString on a variable argument list.

因为Swift字符串在变量参数列表上桥接到NSString,所以可以正常工作。

#2


-4  

This will work:

这将有效:

print("Currently at processing state: \(readingin)")

So you put the parameter you want to print for readingin.

因此,您要将要打印的参数用于阅读。

(If this solved your question please mark it as the answer)

(如果这解决了您的问题,请将其标记为答案)