Formatting string with %@ in Swift Formatting string with %@ in Swift swift swift

Formatting string with %@ in Swift


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.


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


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)