Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Formatter for string constants in Swift?

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.

I would like to print os_log message with string formatter for string constant. Something akin 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")

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.

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.

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.

like image 901
HuaTham Avatar asked Feb 18 '17 12:02

HuaTham


1 Answers

From the os_log man page:

You may 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 bridged to NSString on a variable argument list.

like image 55
Martin R Avatar answered Nov 08 '22 23:11

Martin R