迅速问题顺带可变数量的参数 [英] Swift Issue in passing variable number of parameters

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

问题描述

我有以下的code:

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调用打印变参,函数名和行号。

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

推荐答案

在<相似href=\"http://stackoverflow.com/questions/29399882/swift-function-with-args-pass-to-another-function-with-args\">Swift与ARGS功能...传递给另一个函数ARGS ,
你必须创建一个 CVaListPointer 的va_list 在C雨燕当量),并调用一个函数,它接受一个 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")

我做了格式第一个参数,所以这是没有外部
参数名称。变量参数列表必须是最后一个参数
雨燕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.

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")

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

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