Sprint() in Swift?

Does Swift have an equivalent of the C, and C++, function sprint() which directs its output to a string variable instead of the terminal?

You can use string interpolation for this: Documentation

2 Likes

You can use the to: parameter on print:

var s = ""
print("foo", to: &s)
3 Likes

And if you want the exact replacement to sprintf, here comes String.init(format:_:):

import Foundation

let str = String(format: "%u, %f\n", 1_000_000, 3.1415) // "1000000, 3.141500\n"
3 Likes

Though caution: never use String.init(format:_:) for formatting values for users. Any one hard-coded format for numbers, currencies, dates, etc. is going to be wrong for the majority of people in the world.

Use NumberFormatter, DateFormatter, etc. for those.

6 Likes

Should use the new Foundation FormatStyle: FormatStyle | Apple Developer Documentation

3 Likes