swift-playground/Closures.playground/Contents.swift
2025-01-21 11:27:35 +08:00

56 lines
1.0 KiB
Swift

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:))