Files
SwiftStudy/09 闭包.playground/Contents.swift
2022-01-07 22:16:23 +08:00

122 lines
3.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import UIKit
var greeting = "Hello, playground"
/*:
swift func
Closure Expression
-
{
() -> in
-
:
- 使
- 使
(Closure)
- \
-
- \
-
-
- \
-
class Closure {
var num = 0
func plus(_ i: Int) -> Int { num += i
return num
}
}
var cs1 = Closure()
var cs2 = Closure()
cs1.plus(1) // 1
cs2.plus(2) // 2
cs1.plus(3) // 4
cs2.plus(4) // 6
cs1.plus(5) // 9
cs2.plus(6) // 12
*/
//
var fn = {
(v1: Int, v2: Int) -> Int in
return v1 + v2
}
print(fn(10, 20))
//
//
func exec(v1: Int, v2: Int, fn:(Int, Int) -> Int) {
print(fn(v1, v2))
}
exec(v1: 10, v2: 20) {
$0 + $1
}
//
func exec1(fn:(Int, Int) -> Int) {
print(fn(1, 2))
}
exec1(fn: {$0 + $1})
exec1() {$0 + $1}
exec1{$0 + $1}
//
typealias Fn = (Int) -> Int
func getFn() -> Fn {
var num = 0
func plus(_ i: Int) -> Int { num += i
return num
}
return plus
} // plusnum
var fn1 = getFn() //
var fn2 = getFn() //
fn1(1) // 1
fn2(2) // 2
fn1(3) // 4
fn2(4) // 6
fn1(5) // 9
fn2(6) // 12
//
/*:
@autoclosure 20 { 20 }
@autoclosure () -> T
@autoclosure 1
?? 使 @autoclosure
@autoclosure@autoclosure
*/
// 102
func getFirstPositive(_ v1: Int, _ v2: Int) -> Int {
return v1 > 0 ? v1 : v2
}
getFirstPositive(10, 20) // 10
getFirstPositive(-2, 20) // 20
getFirstPositive(0, -4) // -4
// v2
func getFirstPositive(_ v1: Int, _ v2: () -> Int) -> Int? {
return v1 > 0 ? v1 : v2()
}
getFirstPositive(-4) { 20 }
func getFirstPositive(_ v1: Int, _ v2: @autoclosure () -> Int) -> Int? { return v1 > 0 ? v1 : v2()
}
getFirstPositive(-4, 20)