Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format String with array of Strings

Tags:

arrays

ios

swift

I am trying to create a String with an array of Strings, 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.

like image 932
Daniel Avatar asked Jul 21 '16 17:07

Daniel


2 Answers

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.

like image 106
Martin R Avatar answered Sep 28 '22 16:09

Martin R


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)
like image 36
Rob Avatar answered Sep 28 '22 16:09

Rob