String formatter for string constants in Swift?

Sorry if this is a duplicate, but I tried to search, including Apple String Format Specifiers and IEEE printf spec , but could not find an answer for something so simple.

I would like to print an os_log message with string formatting for a string constant. Something similar to:

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

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

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

he just didn't print anything.

How to print a string constant using a string format specifier? I am not sure how to do this using NSLog .

Edit: os_log requires StaticString , so it cannot do something like "Something \(Expr) Something else" , as in print() . You can use string formatting to print numeric variables. I am wondering how to print string constants / variables in this case.

Edit 2: Apple really discusses this topic on its page, which I managed to skip because it was discussed only in the Objective-C API version.

+5
source share
2 answers

On the os_log man page:

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

In your case

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

works because the Swift string is connected to the bridge before NSString to a list of variable arguments.

+5
source

This will work:

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

So, you put the parameter that you want to print for reading.

(If this resolves your question, mark it as an answer)

-3
source

Source: https://habr.com/ru/post/1264384/


All Articles