func min(_ numbers:Double...)->Double{
var result:Double = 0.0
for num in numbers{
if num < numbers {
result = num
}
}
return result
}
Here in if num < numbers
showing me error:
Binary Operator "<" can not applied to operand of double and Double
Probably, the error that you are mentioning is quite wrong, it should be:
Binary Operator "<" can not applied to operand of Double and [Double]
means that you are trying to compare between a double and an array of doubles (numbers
).
What are you trying to implement should be:
func min(_ numbers: Double...) -> Double? {
guard var result = numbers.first else {
return nil
}
for num in numbers {
if result > num {
result = num
}
}
return result
}
Usage:
if let minResult = min(2.1, 61.2, 33.6, 9.3, 4.2, 6.1, 6.1, 6.1, 3.4) {
print(minResult) // 2.1
}
let nilResult = min() // nil
Note that min
should returns an optional value, because -as mentioned in the code snippet- a function with variadic parameter is able to take 0 parameters without using the label.
Also:
I would recommend to use min() array method, as follows:
func min(_ numbers: Double...) -> Double? {
return numbers.min()
}
The output should be the same...