传递可变数量参数的Swift问题 [英] Swift Issue in passing variable number of parameters

查看:29
本文介绍了传递可变数量参数的Swift问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public static func e(file: String = __FILE__,
    function: String = __FUNCTION__,
    line: Int = __LINE__,format: String, args: CVarArgType...)
{
    NSLog([%d]\t [%@] " + format,line,function, args); //<<< I have no idea how to pass the params here
}

我在 NSLog 上遇到编译器错误,无法像我一样调用.

I get compiler error on NSLog that can not be called as I did.

我只需要使用单个 NSLOG 调用打印 var args、函数名称和行.

Simply I need to print the var args, function name and line using a single NSLOG call.

推荐答案

类似于 带有 args 的 Swift 函数...通过 args 传递给另一个函数,您必须创建一个 CVaListPointer(C 中 va_list 的 Swift 等价物)并调用一个带有 CVaListPointer 参数的函数,在这种情况下 NSLogv().

Similar as in Swift function with args... pass to another function with args, you have to create a CVaListPointer (the Swift equivalent of va_list in C) and call a function which takes a CVaListPointer parameter, in this case NSLogv().

public class Logger {
    public static func e(
        format: String,
        file: String = __FILE__,
        function: String = __FUNCTION__,
        line: Int = __LINE__,
        args: CVarArgType...)
    {
        let extendedFormat = "[%d]\t [%@] " + format
        let extendedArgs : [CVarArgType] = [ line, function ] + args
        withVaList(extendedArgs) { NSLogv(extendedFormat, $0) }
    }
}

// Example usage:
Logger.e("x = %d, y = %f, z = %@", args: 13, 1.23, "foo")

我已经将 format 作为第一个参数,所以它没有外部参数名称.可变参数列表必须是最后一个参数在 Swift 1.2 中,外部参数无法避免结合默认参数.

I have made format the first parameter, so that is has no external parameter name. The variable argument list must be the last parameter in Swift 1.2, and the external parameter cannot be avoided in this combination with default parameters.

Swift 2 中,您可以避免使用外部参数名称可变参数:

In Swift 2 you can avoid the external parameter name for the variable arguments:

public class Logger {
    public static func e(
        format: String,
        _ args: CVarArgType...,
        file: String = __FILE__,
        function: String = __FUNCTION__,
        line: Int = __LINE__)
    {
        let extendedFormat = "[%d]\t [%@] " + format
        let extendedArgs : [CVarArgType] = [ line, function ] + args
        withVaList(extendedArgs) { NSLogv(extendedFormat, $0) }
    }
}

// Example usage:
Logger.e("x = %d, y = %f, z = %@", 13, 1.23, "foo")

这篇关于传递可变数量参数的Swift问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆