Finish Closures

This commit is contained in:
Gary Gan 2025-01-21 11:27:35 +08:00
parent 03cf181454
commit 10812798ca
3 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,55 @@
import Foundation
func add(_ lhs: Int, _ rhs: Int) -> Int {
lhs + rhs
}
let addClosure: (Int, Int) -> Int
= { (lhs: Int, rhs: Int) -> Int in
lhs + rhs
}
addClosure(20, 30)
func customAdd(_ lhs: Int, _ rhs: Int, using function: (Int, Int) -> Int) -> Int{
return function(lhs, rhs)
}
customAdd(20, 30, using: addClosure)
customAdd(20, 30, using: { (lhs: Int, rhs: Int) -> Int in lhs + rhs})
customAdd(20, 30) { (rhs, lhs) in
rhs + lhs
}
customAdd(20, 30) { $0 + $1 }
let ages = [2, 3, 54, 24, 512, 63, 32]
ages.sorted(by: {(lhs: Int, rhs:Int) -> Bool in lhs < rhs})
ages.sorted(by: <)
ages.sorted(by: >)
func customAdd2(using function: (Int, Int) -> Int, _ lhs: Int, _ rhs: Int) -> Int{
return function(lhs, rhs)
}
customAdd2(using: { (lhs, rhs) in lhs + rhs}, 20, 30)
customAdd(30, 10, using: +)
func doAddition(on value: Int, using function: (Int) -> Int) -> Int {
function(value)
}
doAddition(on: 30) { (value) in
value + 60
}
func add20To(value: Int) -> Int {
value + 20
}
doAddition(on: 10, using: add20To(value:))

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='7.0' target-platform='macos' swift-version='6' buildActiveScheme='true' executeOnSourceChanges='true' importAppTypes='true'/>

View File

@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Closures.playground">
</FileRef>
<FileRef
location = "group:Functions.playground">
</FileRef>