Swift function with args… pass to another function with args

点点圈 提交于 2019-11-27 16:14:49

问题


I have a simple problem. I tried search in many blogs about this question but all site return how function in swift work, but I need this case.

My custom function is:

func getLocalizeWithParams(args:CVarArgType...)->String {
     return NSString.localizedStringWithFormat(self, args); //error: Expected expression in list of expressions
}

How I do to pass my args to other system function with args?

Thanks advance.


回答1:


Similar as in (Objective-)C, you cannot pass a variable argument list directly to another function. You have to create a CVaListPointer (the Swift equivalent of va_list in C) and call a function which takes a CVaListPointer parameter.

So this could be what you are looking for:

extension String {
    func getLocalizeWithParams(args : CVarArgType...) -> String {
        return withVaList(args) {
            NSString(format: self, locale: NSLocale.currentLocale(), arguments: $0)
        } as String
    }
}

withVaList() creates a CVaListPointer from the given argument list and calls the closure with this pointer as argument.

Example (from the NSString documentation):

let msg = "%@:  %f\n".getLocalizeWithParams("Cost", 1234.56)
print(msg)

Output for US locale:

Cost:  1,234.560000

Output for German locale:

Cost:  1.234,560000

Update: As of Swift 3/4/5 one can pass the arguments to

String(format: String, locale: Locale?, arguments: [CVarArg])

directly:

extension String {
    func getLocalizeWithParams(_ args : CVarArg...) -> String {
        return String(format: self, locale: .current, arguments: args)
    }
}



回答2:


I believe you're using NSString.localizedStringWithFormat(self, args) incorrectly. Otherwise nothing wrong with using args to call another function.

If you look below, you need to specify the format as NSString as the first argument: NSString.localizedStringWithFormat(format: NSString, args: CVarArgType...)

This SO question explains how to use it in Swift: iOS Swift and localizedStringWithFormat



来源:https://stackoverflow.com/questions/29399882/swift-function-with-args-pass-to-another-function-with-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!