oyalhi oyalhi - 1 year ago 126
Swift Question

Formatting string with %@ in Swift

I have the following class with private struct for strings which I would like to use them for formatted strings later on. However, the code crashes at run time.

Why is this? Is it because it is defined as static let?

Below is the stripped code:

class LGNotificationHandler {
private struct Strings {
static let SentImagesENG = "Sent %@ images to the event"
static let SentImagesTUR = "Etkinliğe %@ görsel gönderdi"

func buildNotificationString(imageCount: Int) -> String {
if imageCount == 1 {

} else {
// below line is giving error at run time
notificationENG = String(format: Strings.SentImagesENG, imageCount)
notificationTUR = String(format: Strings.SentImagesTUR, imageCount)

Answer Source

You neglected to provide any details about the crash but one obvious problem is the use of the %@ format specifier with an Int. You need to use %d with Int.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download