- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 296字
- 2021-07-02 23:54:26
Functions
Functions are self-contained blocks of code that perform a specific task.
In Swift, functions are first-class citizens, meaning that they can be stored, passed, and returned. Functions can be curried and defined as higher-order functions that take other functions as their arguments.
Functions in Swift can have multiple input parameters and multiple returns using tuples. Let's look at the following example:
func greet(name: String, day: String) ->String {
return "Hello \(name), today is \(day)"
}
greet(name: "Francois", day:"Saturday")
Functions can have variadic parameters. Consider the following example:
// Variable number of arguments in functions - Variadic Parameters
func sumOf(numbers: Int...) -> (Int, Int) {
var sum = 0
var counter = 0
for number in numbers {
sum += number
counter += 1
}
return (sum, counter)
}
sumOf()
sumOf(numbers: 7, 9, 45)
Functions can have in-out parameters. Consider the following example:
func swapTwoInts ( a: inout Int, b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
The in-out parameters are not favorable in functional Swift as they mutate states and make functions impure.
In Swift, we can define nested functions. The following example presents a function named add nested inside another function. Nested functions can access the data in scope of their parent function. In this example, the add function has access to the y variable:
func returnTwenty() ->Int {
var y = 10
func add() {
y += 10
}
add()
return y
}
returnTwenty()
In Swift, functions can return other functions. In the following example, the makeIncrementer function returns a function that receives an Int value and returns an Int value (Int ->Int):
func makeIncrementer() -> ((Int) ->Int) {
func addOne(number: Int) ->Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
- Hands-On Data Structures and Algorithms with Rust
- 大數(shù)據(jù)技術(shù)基礎(chǔ)
- 從0到1:數(shù)據(jù)分析師養(yǎng)成寶典
- 企業(yè)大數(shù)據(jù)系統(tǒng)構(gòu)建實戰(zhàn):技術(shù)、架構(gòu)、實施與應(yīng)用
- Access 2007數(shù)據(jù)庫應(yīng)用上機(jī)指導(dǎo)與練習(xí)
- Learning JavaScriptMVC
- R數(shù)據(jù)科學(xué)實戰(zhàn):工具詳解與案例分析(鮮讀版)
- Access 2016數(shù)據(jù)庫技術(shù)及應(yīng)用
- iOS and OS X Network Programming Cookbook
- Python醫(yī)學(xué)數(shù)據(jù)分析入門
- 數(shù)據(jù)庫技術(shù)實用教程
- Oracle PL/SQL實例精解(原書第5版)
- 數(shù)據(jù)中心數(shù)字孿生應(yīng)用實踐
- Python數(shù)據(jù)分析與挖掘?qū)崙?zhàn)(第3版)
- 新手學(xué)會計(2013-2014實戰(zhàn)升級版)