Swift编程:函数、闭包、风格约定及正则表达式与RxSwift的应用
1. 函数作为一等公民
在Swift中,函数作为一等公民,意味着它可以像对象一样享有特权。它可以被赋值给变量、作为参数传递给函数,或者作为函数的返回类型。
1.1 将函数赋值给变量
以下是一个示例代码:
struct Mathematics {
internal func performOperation(inputArray: [Int], operation: (Int) -> Int) -> [Int] {
var processedArray = [Int]()
for item in inputArray {
processedArray.append(operation(item))
}
return processedArray
}
internal func performComplexOperation(valueOne: Int) -> ((Int) -> Int) {
return {
return valueOne + $0
}
}
}
let arrayToBeProcessed = [1,3,5,7,9,11,8,6,4,2,100]
let math = Mathematics()
func add2(item: Int) -> Int {
return (item + 2)
}
//
超级会员免费看
订阅专栏 解锁全文
19

被折叠的 条评论
为什么被折叠?



