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

前端 未结 6 920
广开言路
广开言路 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条回答
  •  情深已故
    2021-02-19 14:07

    I tried mcfedr's code. Somehow, my Xcode 11 treated CVarArgType as undeclared type, so I investigated into this for a while.

    I didn't not understand the closure part of his/her code. And, I just simplified to hard casted each element to CVarArg using as! operator.

    func format(key: String, args: [Any]) -> String {
        return String(format: key, arguments: args.map { ($0 as! CVarArg) })
    }
    
    let doubleValue: Double = 1.25
    let floatValue: Float = 2.75
    let intValue: Int = 3
    let numberValue: NSNumber = 4.5 as NSNumber
    let hello: String = "Hello"
    let world: NSString = "World" as NSString
    print(format(key: "double: %f, float: %f, int: %d, number: %@, %@, %@", args: [doubleValue, floatValue, intValue, numberValue, hello, world]))
    
    // double: 1.250000, float: 2.750000, int: 3, number: 4.5, Hello, World
    

    It seems it's working fine under swift 5.1, but there may be some pitfalls.

提交回复
热议问题