We have some code today that takes an NSArray and passes it as a argument list to -[NSString initWithFormat:arguments] and we\'re trying to get this to work with ARC. Here\'s th
Expanding on @mcfedr's answer, this Swift 3 helper does the job:
import Foundation
@objc (FTStringFormat) public class StringFormat: NSObject {
@objc public class func format(key: String, args: [AnyObject]) -> String {
let locArgs: [CVarArg] = args.flatMap({ (arg: AnyObject) -> CVarArg? in
if let arg = arg as? NSNumber {
return arg.intValue
}
if let arg = arg as? CustomStringConvertible {
return arg.description
}
return nil
});
return String(format: key, arguments: locArgs)
}
}
Calling from Objective-C:
[FTStringFormat formatWithKey:@"name: %@ age: %d" args:@[@"John", @(42)]]
For the %@
format specifier we're using Swift's CustomStringConvertible
protocol in order to call description
on all of the array members.
Supporting all number format specifiers like %d
and %f
is not really possible because the NSNumber
object doesn't reveal if it's an integer or float. So we could only support one or the other. Here we use intValue
, so %d
is supported but %f
and %g
are not.