- 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)
- 數(shù)據(jù)庫技術(shù)與應(yīng)用教程(Access)
- 使用GitOps實現(xiàn)Kubernetes的持續(xù)部署:模式、流程及工具
- UDK iOS Game Development Beginner's Guide
- Hadoop大數(shù)據(jù)實戰(zhàn)權(quán)威指南(第2版)
- OracleDBA實戰(zhàn)攻略:運維管理、診斷優(yōu)化、高可用與最佳實踐
- 大數(shù)據(jù)架構(gòu)和算法實現(xiàn)之路:電商系統(tǒng)的技術(shù)實戰(zhàn)
- 深入淺出 Hyperscan:高性能正則表達式算法原理與設(shè)計
- Instant Autodesk AutoCAD 2014 Customization with .NET
- 數(shù)字IC設(shè)計入門(微課視頻版)
- MySQL技術(shù)內(nèi)幕:SQL編程
- 爬蟲實戰(zhàn):從數(shù)據(jù)到產(chǎn)品
- 大數(shù)據(jù)技術(shù)原理與應(yīng)用:概念、存儲、處理、分析與應(yīng)用
- Spring Boot 2.0 Cookbook(Second Edition)
- 數(shù)字化轉(zhuǎn)型實踐:構(gòu)建云原生大數(shù)據(jù)平臺
- 數(shù)據(jù)庫原理及應(yīng)用:SQL Server 2016