simpleBob simpleBob - 4 months ago 45
iOS Question

format String with array of Strings

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.

Answer

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.

Comments