Variadic fonksiyonlar
Variadic fonksiyonlar
, aynı türden ancak herhangi bir sayıda parametre kabul edebilen fonksiyonlardır. Örneğin aritmetik ortalama hesaplayan bir fonksiyon üzerinden gösterelim.
Önce variadic fonksiyon
özelliğini kullanmadan ekleyelim. Daha sonra da variadic halini yazalım.
func arithmeticMean(_ numbers: [Double]) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean([1, 2, 3, 4, 5])
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean([3, 8.25, 18.75])
// returns 10.0, which is the arithmetic mean of these three numbers
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers
Fonksiyon içerisinde print(type(of: numbers))
ile kontrol edilirse numbers değişkenin //Array<Double>
şeklinde döndügü görülecektir.
Ek bilgi kullandıgımız print fonksiyonu da variadic foksiyondur.
F Void print(items: Any...)
Functions — The Swift Programming Language (Swift 5.7)