Reputation: 3994
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)
}
}
}
Upvotes: 18
Views: 35156
Reputation: 3342
Update Shorter version
extension String {
func format(_ arguments: CVarArg...) -> String {
let args = arguments.map { String(describing: $0) } as [CVarArg]
return String.init(format: self, arguments: args)
}
}
You can use this extension
Swift 5
extension String {
func format(_ arguments: CVarArg...) -> String {
let args = arguments.map {
if let arg = $0 as? Int { return String(arg) }
if let arg = $0 as? Float { return String(arg) }
if let arg = $0 as? Double { return String(arg) }
if let arg = $0 as? Int64 { return String(arg) }
if let arg = $0 as? String { return String(arg) }
if let arg = $0 as? Character { return String(arg) }
return "(null)"
} as [CVarArg]
return String.init(format: self, arguments: args)
}
}
Using:
let txt = "My name is %@, I am %@ years old".format("Mickael", 24)
Upvotes: 9
Reputation: 9226
You need to replace %@ with %d. ImageCount is Int
value. so use %d instead of %@.
Format specifier:
%d - int Value
%f - float value
%ld - long value
%@ - string value and for many more.
For see all Format Specifiers see Apple Doc Format Specifiers
Upvotes: 20
Reputation: 318874
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
.
Upvotes: 22