Junior
Existujú funkcie prvej triedy v programovacom jazyku Swift?
sobes.tech AI
Odpoveď od AI
Da, v Swiftu so funkcije funkcije prvega razreda.
To pomeni, da lahko funkcije:
- Dodelijo se spremenljivkam in konstantam.
- Se prenesejo kot argumenti drugim funkcijam.
- Se vrnejo iz drugih funkcij.
Primer dodeljevanja funkcije spremenljivki:
func greet(name: String) -> String {
return "Živjo, \(name)!"
}
let greetingFunction = greet
print(greetingFunction("Svet")) // Izpis: Živjo, Svet!
Primer prenosa funkcije kot argumenta:
func applyOperation(value: Int, operation: (Int) -> Int) -> Int {
return operation(value)
}
func double(number: Int) -> Int {
return number * 2
}
let result = applyOperation(value: 5, operation: double)
print(result) // Izpis: 10
Primer vračanja funkcije iz druge funkcije:
func makeMultiplier(factor: Int) -> (Int) -> Int {
func multiplier(number: Int) -> Int {
return number * factor
}
return multiplier
}
let multiplyByThree = makeMultiplier(factor: 3)
print(multiplyByThree(4)) // Izpis: 12