Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variadic parameter in swift?

Tags:

swift

I know I can call print directly, but why pass items to another function make it like wrapped by Array? I wanna know why and how to fix it

func test(items:Any...) {
  print(items)
}

test(1,2,3)     // print [1,2,3]
print(1, 2,3)   // print 1 2 3

How to make test function act like print function?

like image 475
user49354 Avatar asked Oct 19 '22 02:10

user49354


2 Answers

Finally, I wrap test like this:

func test( items:Any...) {
    for num in items {
        print("\(num) ", separator:" ", terminator:"")
    }
    print("")
}

And this works fine, But Any better solutions?

like image 65
user49354 Avatar answered Jan 04 '23 07:01

user49354


If you want to make test do the same thing as print, why not just call print?

func test(args: Any...) {
    print(args)
}

If you are not allowed/don't want to use this little trick, you can try this. But this only works with CustomStringConvertible:

func test(args: CustomStringConvertible...) {

    print(args.map {
        $0.description
    }.joinWithSeparator(" "))

}
like image 30
Sweeper Avatar answered Jan 04 '23 07:01

Sweeper