I am trying to create a String
with an array of String
s, I would expect this to work:
let format = "%@ and %@!"
let str1 = "bla"
let str2 = "blob"
private func formatItNicely(format: String, substrings: [String]) -> String {
return String(format: format, arguments: substrings)
}
let result = formatItNicely(format, substrings: [str1, str2])
but I am getting fatal error: can't unsafeBitCast between types of different sizes
.
I have seen this and this and this questions (and many more), but I still don't know how to accomplish what I am trying to do.
String(format:, arguments: )
expects a [CVarArgType]
as the second
parameter:
let format = "%@ and %@!"
let str1 = "bla"
let str2 = "blob"
private func formatItNicely(format: String, substrings: [CVarArgType]) -> String {
return String(format: format, arguments: substrings)
}
let result = formatItNicely(format, substrings: [str1, str2])
print(result) // bla and blob!
But note that this can crash (or give unexpected output) if the format specifiers do not match the actual arguments, the formatting functions do not (cannot) check that.
Or you can use the variadic rendition:
private func formatItNicely(format: String, _ arguments: CVarArgType...) -> String {
return String(format: format, arguments: arguments)
}
Calling it like so:
let format = "%@ and %@!"
let str1 = "bla"
let str2 = "blob"
let result = formatItNicely(format, str1, str2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With