Why call it when nothing is passed and nothing is done? Do the check before the call.
Except that currently in Swift, you can't do the check before because you can't pass an array where a list of variadic parameters is expected.
func squareVariadic(numbers: Int...) {
for number in numbers {
print("\(number) squared is \(number*number)")
}
}
let arrayOfNumbers: [Int] = []
if !arrayOfNumbers.isEmpty {
squareVariadic(numbers: arrayOfNumbers)
} else {
print("Nothing was passed inside variadic function.")
}
This results in a compiler error: Cannot pass array of type '[Int]' as variadic arguments of type 'Int'
There have been proposals to correct this (say, with something like Python's "splat" operator to expand or unpack an array into its elements), but the Swift team is holding off while the design of how variadic generics should work is hashed out.
It often makes more sense to do those kinds of checks inside a function anyway. That minimizes the amount of things the programmer has to know to do before using the function and presents a cleaner API.
This is exactly the kind of situation that the guard
statement is for. (Sorry if this doesn't make sense yet, @rabinexpressoSwift; I'm not sure on which of the 100 Days guard
gets covered)
func squareVariadic(numbers: Int...) {
guard !numbers.isEmpty else {
print("Nothing was passed inside variadic function.")
return
}
for number in numbers {
print("\(number) squared is \(number*number)")
}
}
let arrayOfNumbers: [Int] = []
squareVariadic(numbers: arrayOfNumbers)
Which still won't compile for the same reason as before but is a cleaner API with less cognitive load when using it. Instead of having to remember to check that your array isn't empty before you call squareVariadic
, you just pass the array and let squareVariadic
handle it appropriately.
To answer the original question:
Hi, how do i edit the below error code such that when calling the variadic function with no parameter value, i can print - "Nothing was passed inside variadic function".
The way to call squareVariadic
with zero parameters is to just leave the variadic argument out of the call and check for an empty array inside the function, either by checking for numbers.isEmpty
or using a guard
:
func squareVariadic(numbers: Int...) {
if numbers.isEmpty {
print("Nothing was passed inside variadic function.")
} else {
for number in numbers {
print("\(number) squared is \(number*number)")
}
}
}
or:
func squareVariadic(numbers: Int...) {
guard !numbers.isEmpty else {
print("Nothing was passed inside variadic function.")
return
}
for number in numbers {
print("\(number) squared is \(number*number)")
}
}
And then call it like so:
squareVariadic()
//prints Nothing was passed inside variadic function.