Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)  
        }
    }
}
like image 501
oyalhi Avatar asked Nov 16 '16 07:11

oyalhi


People also ask

What is string interpolation in Swift?

Swift String Interpolation 2) Means the string is created from a mix of constants, variables, literals or expressions. Example: let length:Float = 3.14 var breadth = 10 var myString = "Area of a rectangle is length*breadth" myString = "\(myString) i.e. = \(length)*\(breadth)"


1 Answers

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.

like image 103
rmaddy Avatar answered Oct 25 '22 01:10

rmaddy