Swift中方法使用可变参数

Swift中如何实现可变参数呢?如下定义的方法:

如UIAlertView的初始化方法,形参moreButtonTitles被定义为可变参数。

public convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)

如何在自定义的方法中使用可变参数呢?下面用代码展示:

//定义一个带可变参数的方法
func appendStr( string:String,otherString:String ...){
    var str = string
    str += otherString.reduce("", { (a, b) -> String in
        return a + " " + b
    })
    print(str)
}
//方法调用
appendStr(string: "哈哈", otherString: "Hello","Word","OK")

打印返回结果:

哈哈 Hello Word OK

此时可变参数otherString其实是一个数组,看下它的类型

type(of: otherString) 为 Array

OC的可变参数使用

你可能感兴趣的:(Swift中方法使用可变参数)