Converting NSArray Contents to a varargs (With ARC) For Use With NSString initWithFormat

前端 未结 6 918
广开言路
广开言路 2021-02-19 13:43

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

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 14:23

    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.

提交回复
热议问题